From a9a8c6b095de0890240325b7e437e40303720aa3 Mon Sep 17 00:00:00 2001 From: Luiz Felipe Weber Date: Wed, 25 Nov 2015 17:36:22 -0200 Subject: [PATCH] =?UTF-8?q?Corre=C3=A7=C3=A3o=20notifica=C3=A7=C3=A3o=20de?= =?UTF-8?q?=20retorno?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agora usa a nova api do Pagseguro para alterar o status das transações de pedidos. --- PagSeguroLibrary/PagSeguroLibrary.class.php | 119 +++ PagSeguroLibrary/PagSeguroLibrary.php | 26 + .../config/PagSeguroConfig.class.php | 215 +++++ .../config/PagSeguroConfigWrapper.php | 149 ++++ .../PagSeguroAcceptPaymentMethod.class.php | 81 ++ ...gSeguroAcceptedPaymentMethodName.class.php | 105 +++ .../PagSeguroAcceptedPaymentMethods.class.php | 71 ++ .../PagSeguroAcceptedPayments.class.php | 48 ++ .../PagSeguroAccountCredentials.class.php | 111 +++ .../domain/PagSeguroAddress.class.php | 328 ++++++++ .../PagSeguroApplicationCredentials.class.php | 144 ++++ .../domain/PagSeguroAuthorization.class.php | 191 +++++ .../PagSeguroAuthorizationAccount.class.php | 67 ++ ...PagSeguroAuthorizationPermission.class.php | 117 +++ ...agSeguroAuthorizationPermissions.class.php | 77 ++ .../PagSeguroAuthorizationRequest.class.php | 226 ++++++ ...gSeguroAuthorizationSearchResult.class.php | 158 ++++ .../domain/PagSeguroBilling.class.php | 67 ++ .../domain/PagSeguroCredentials.class.php | 39 + .../domain/PagSeguroCreditCard.class.php | 140 ++++ .../PagSeguroCreditCardCheckout.class.php | 170 ++++ .../PagSeguroCreditCardHolder.class.php | 180 +++++ .../domain/PagSeguroCurrencies.class.php | 101 +++ .../PagSeguroDirectPaymentMethods.class.php | 78 ++ .../PagSeguroDirectPaymentRequest.class.php | 292 +++++++ .../domain/PagSeguroDocument.class.php | 102 +++ .../domain/PagSeguroDocuments.class.php | 83 ++ .../domain/PagSeguroError.class.php | 86 ++ .../PagSeguroExcludePaymentMethod.class.php | 83 ++ .../domain/PagSeguroHttpStatus.class.php | 90 +++ .../domain/PagSeguroInstallment.class.php | 103 +++ .../domain/PagSeguroInstallments.class.php | 219 +++++ .../domain/PagSeguroItem.class.php | 190 +++++ .../domain/PagSeguroMetaData.class.php | 71 ++ .../domain/PagSeguroMetaDataItem.class.php | 146 ++++ .../PagSeguroMetaDataItemKeys.class.php | 88 ++ .../PagSeguroNotificationType.class.php | 75 ++ .../PagSeguroOnlineDebitCheckout.class.php | 66 ++ .../domain/PagSeguroParameter.class.php | 65 ++ .../domain/PagSeguroParameterItem.class.php | 120 +++ .../domain/PagSeguroPaymentMethod.class.php | 98 +++ .../PagSeguroPaymentMethodCode.class.php | 202 +++++ .../PagSeguroPaymentMethodConfig.class.php | 71 ++ ...PagSeguroPaymentMethodConfigItem.class.php | 121 +++ ...PagSeguroPaymentMethodConfigKeys.class.php | 80 ++ .../PagSeguroPaymentMethodGroups.class.php | 82 ++ .../PagSeguroPaymentMethodType.class.php | 91 +++ .../domain/PagSeguroPaymentMode.class.php | 86 ++ .../domain/PagSeguroPaymentRequest.class.php | 97 +++ .../domain/PagSeguroPhone.class.php | 114 +++ .../domain/PagSeguroPreApproval.class.php | 287 +++++++ .../PagSeguroPreApprovalCharge.class.php | 159 ++++ .../PagSeguroPreApprovalRequest.class.php | 364 +++++++++ ...PagSeguroPreApprovalSearchResult.class.php | 50 ++ .../PagSeguroPreApprovalStatus.class.php | 111 +++ .../domain/PagSeguroRequest.class.php | 754 ++++++++++++++++++ .../domain/PagSeguroSearchResult.class.php | 135 ++++ .../domain/PagSeguroSender.class.php | 203 +++++ .../domain/PagSeguroSenderDocument.class.php | 102 +++ .../domain/PagSeguroSession.class.php | 66 ++ .../domain/PagSeguroShipping.class.php | 119 +++ .../domain/PagSeguroShippingType.class.php | 119 +++ .../domain/PagSeguroTransaction.class.php | 605 ++++++++++++++ ...uroTransactionCancellationSource.class.php | 103 +++ ...PagSeguroTransactionCreditorFees.class.php | 80 ++ ...PagSeguroTransactionSearchResult.class.php | 53 ++ .../PagSeguroTransactionStatus.class.php | 111 +++ .../PagSeguroTransactionSummary.class.php | 353 ++++++++ .../domain/PagSeguroTransactionType.class.php | 82 ++ .../PagSeguroServiceException.class.php | 136 ++++ .../helper/PagSeguroHelper.class.php | 175 ++++ .../loader/PagSeguroAutoLoader.class.php | 73 ++ PagSeguroLibrary/log/LogPagSeguro.class.php | 210 +++++ .../PagSeguroAuthorizationParser.class.php | 219 +++++ .../parser/PagSeguroCancelParser.class.php | 39 + .../PagSeguroDirectPaymentParser.class.php | 141 ++++ .../PagSeguroInstallmentParser.class.php | 79 ++ .../parser/PagSeguroParserData.class.php | 104 +++ .../parser/PagSeguroPaymentParser.class.php | 283 +++++++ .../PagSeguroPreApprovalParser.class.php | 335 ++++++++ .../parser/PagSeguroRefundParser.class.php | 40 + .../parser/PagSeguroServiceParser.class.php | 52 ++ .../parser/PagSeguroSessionParser.class.php | 48 ++ .../PagSeguroTransactionParser.class.php | 449 +++++++++++ .../resources/PagSeguroResources.class.php | 214 +++++ .../resources/PagSeguroResources.php | 101 +++ ...SeguroAuthorizationSearchService.class.php | 287 +++++++ .../PagSeguroAuthorizationService.class.php | 149 ++++ .../service/PagSeguroCancelService.class.php | 116 +++ .../service/PagSeguroConnectionData.class.php | 321 ++++++++ .../PagSeguroDirectPaymentService.class.php | 136 ++++ .../PagSeguroInstallmentService.class.php | 125 +++ .../PagSeguroNotificationService.class.php | 253 ++++++ .../service/PagSeguroPaymentService.class.php | 127 +++ ...agSeguroPreApprovalSearchService.class.php | 432 ++++++++++ .../PagSeguroPreApprovalService.class.php | 304 +++++++ .../service/PagSeguroRefundService.class.php | 104 +++ .../service/PagSeguroSessionService.class.php | 101 +++ ...agSeguroTransactionSearchService.class.php | 427 ++++++++++ .../utils/PagSeguroHttpConnection.class.php | 130 +++ .../utils/PagSeguroXmlParser.class.php | 113 +++ pagseguro_virtuemartbrasil.php | 165 ++-- pagseguro_virtuemartbrasil.xml | 9 +- 103 files changed, 15689 insertions(+), 93 deletions(-) create mode 100644 PagSeguroLibrary/PagSeguroLibrary.class.php create mode 100644 PagSeguroLibrary/PagSeguroLibrary.php create mode 100644 PagSeguroLibrary/config/PagSeguroConfig.class.php create mode 100644 PagSeguroLibrary/config/PagSeguroConfigWrapper.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAcceptPaymentMethod.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethodName.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethods.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAcceptedPayments.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAccountCredentials.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAddress.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroApplicationCredentials.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAuthorization.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAuthorizationAccount.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAuthorizationPermission.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAuthorizationPermissions.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAuthorizationRequest.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroAuthorizationSearchResult.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroBilling.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroCredentials.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroCreditCard.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroCreditCardCheckout.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroCreditCardHolder.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroCurrencies.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroDirectPaymentMethods.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroDirectPaymentRequest.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroDocument.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroDocuments.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroError.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroExcludePaymentMethod.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroHttpStatus.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroInstallment.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroInstallments.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroItem.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroMetaData.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroMetaDataItem.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroMetaDataItemKeys.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroNotificationType.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroOnlineDebitCheckout.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroParameter.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroParameterItem.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMethod.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMethodCode.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMethodConfig.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigItem.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigKeys.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMethodGroups.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMethodType.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentMode.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPaymentRequest.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPhone.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPreApproval.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPreApprovalCharge.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPreApprovalRequest.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPreApprovalSearchResult.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroPreApprovalStatus.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroRequest.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroSearchResult.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroSender.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroSenderDocument.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroSession.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroShipping.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroShippingType.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroTransaction.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroTransactionCancellationSource.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroTransactionCreditorFees.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroTransactionSearchResult.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroTransactionStatus.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroTransactionSummary.class.php create mode 100644 PagSeguroLibrary/domain/PagSeguroTransactionType.class.php create mode 100644 PagSeguroLibrary/exception/PagSeguroServiceException.class.php create mode 100644 PagSeguroLibrary/helper/PagSeguroHelper.class.php create mode 100644 PagSeguroLibrary/loader/PagSeguroAutoLoader.class.php create mode 100644 PagSeguroLibrary/log/LogPagSeguro.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroAuthorizationParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroCancelParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroDirectPaymentParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroInstallmentParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroParserData.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroPaymentParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroPreApprovalParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroRefundParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroServiceParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroSessionParser.class.php create mode 100644 PagSeguroLibrary/parser/PagSeguroTransactionParser.class.php create mode 100644 PagSeguroLibrary/resources/PagSeguroResources.class.php create mode 100644 PagSeguroLibrary/resources/PagSeguroResources.php create mode 100644 PagSeguroLibrary/service/PagSeguroAuthorizationSearchService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroAuthorizationService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroCancelService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroConnectionData.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroDirectPaymentService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroInstallmentService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroNotificationService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroPaymentService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroPreApprovalSearchService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroPreApprovalService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroRefundService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroSessionService.class.php create mode 100644 PagSeguroLibrary/service/PagSeguroTransactionSearchService.class.php create mode 100644 PagSeguroLibrary/utils/PagSeguroHttpConnection.class.php create mode 100644 PagSeguroLibrary/utils/PagSeguroXmlParser.class.php diff --git a/PagSeguroLibrary/PagSeguroLibrary.class.php b/PagSeguroLibrary/PagSeguroLibrary.class.php new file mode 100644 index 0000000..c4d0679 --- /dev/null +++ b/PagSeguroLibrary/PagSeguroLibrary.class.php @@ -0,0 +1,119 @@ +getConfig(); + } else { + throw new Exception("Config is undefined."); + } + } + + public static function init() + { + if (self::$config == null) { + self::$config = new PagSeguroConfig(); + } + + return self::$config; + } + + public static function getData($key1, $key2 = null) + { + if ($key2 != null) { + if (isset(self::$data[$key1][$key2])) { + return self::$data[$key1][$key2]; + } else { + throw new Exception("Keys {$key1}, {$key2} not found."); + } + } else { + if (isset(self::$data[$key1])) { + return self::$data[$key1]; + } else { + throw new Exception("Config key {$key1} not found."); + } + } + } + + public static function setData($key1, $key2, $value) + { + if (isset(self::$data[$key1][$key2])) { + self::$data[$key1][$key2] = $value; + } else { + throw new Exception("Keys {$key1}, {$key2} not found."); + } + } + + public static function setEnvironment($value) + { + self::$data['environment'] = $value; + } + + public static function getApplicationCredentials() + { + if (isset(self::$data['credentials']) && + isset(self::$data['credentials']['appId'][self::$data['environment']]) && + isset(self::$data['credentials']['appKey'][self::$data['environment']]) + ) { + return new PagSeguroApplicationCredentials( + self::$data['credentials']['appId'][self::$data['environment']], + self::$data['credentials']['appKey'][self::$data['environment']] + ); + } else { + throw new Exception("Applications credentials not set."); + } + } + + public static function getAccountCredentials() + { + if (isset(self::$data['credentials']) && + isset(self::$data['credentials']['email']) && + isset(self::$data['credentials']['token'][self::$data['environment']]) + ) { + return new PagSeguroAccountCredentials( + self::$data['credentials']['email'], + self::$data['credentials']['token'][self::$data['environment']] + ); + } else { + throw new Exception("Credentials not set."); + } + } + + public static function getPaymentRedirectUrl() + { + return PagSeguroResources::getPaymentUrl(self::$data['environment']); + } + + public static function getStaticUrl() + { + return PagSeguroResources::getStaticUrl(self::$data['environment']); + } + + public static function getEnvironment() + { + if (isset(self::$data['environment'])) { + return self::$data['environment']; + } else { + throw new Exception("Environment not set."); + } + } + + public static function getApplicationCharset() + { + if (isset(self::$data['application']) && isset(self::$data['application']['charset'])) { + return self::$data['application']['charset']; + } else { + throw new Exception("Application charset not set."); + } + } + + public static function setApplicationCharset($charset) + { + self::setData('application', 'charset', $charset); + } + + public static function logIsActive() + { + if (isset(self::$data['log']) && isset(self::$data['log']['active'])) { + return (bool) self::$data['log']['active']; + } else { + throw new Exception("Log activation flag not set."); + } + } + + public static function activeLog($fileName = null) + { + self::setData('log', 'active', true); + self::setData('log', 'fileLocation', $fileName ? $fileName : ''); + LogPagSeguro::reLoad(); + } + + public static function getLogFileLocation() + { + if (isset(self::$data['log']) && isset(self::$data['log']['fileLocation'])) { + return self::$data['log']['fileLocation']; + } else { + throw new Exception("Log file location not set."); + } + } + + /*** + * Validate if the requirements are enable for use correct of the PagSeguro + * @return array + */ + public static function validateRequirements() + { + + $requirements = array( + 'version' => '', + 'spl' => '', + 'curl' => '', + 'dom' => '' + ); + + $version = str_replace('.', '', phpversion()); + + if ($version < 5427) { + $requirements['version'] = 'PagSeguroLibrary: PHP version 5.4.27 or greater is required.'; + } + + if (!function_exists('spl_autoload_register')) { + $requirements['spl'] = 'PagSeguroLibrary: Standard PHP Library (SPL) is required.'; + } + + if (!function_exists('curl_init')) { + $requirements['curl'] = 'PagSeguroLibrary: cURL library is required.'; + } + + if (!class_exists('DOMDocument')) { + $requirements['dom'] = 'PagSeguroLibrary: DOM XML extension is required.'; + } + + return $requirements; + } +} diff --git a/PagSeguroLibrary/config/PagSeguroConfigWrapper.php b/PagSeguroLibrary/config/PagSeguroConfigWrapper.php new file mode 100644 index 0000000..11a129d --- /dev/null +++ b/PagSeguroLibrary/config/PagSeguroConfigWrapper.php @@ -0,0 +1,149 @@ +setName($name); + } + if (isset($group) && !PagSeguroHelper::isEmpty($group)) { + $this->setGroup($group); + } + } + + /** + * @return mixed + */ + public function getName() + { + return $this->name; + } + + /** + * @param $name + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return mixed + */ + public function getGroup() + { + return $this->group; + } + + /** + * @param $group + */ + public function setGroup($group) + { + $this->group = $group; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethodName.class.php b/PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethodName.class.php new file mode 100644 index 0000000..3807359 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethodName.class.php @@ -0,0 +1,105 @@ + 'Bradesco debit', + 'DEBITO_ITAU' => 'Itaú debit', + 'DEBITO_UNIBANCO' => 'Unibanco debit', + 'DEBITO_BANCO_BRASIL' => 'Banco do Brasil debit', + 'DEBITO_BANRISUL' => 'Banrisul debit', + 'DEBITO_HSBC' => 'HSBC bank debit', + 'BOLETO' => 'Boleto', + 'VISA' => 'Visa brand', + 'MASTERCARD' => 'MasterCard brand', + 'AMEX' => 'Amex brand', + 'DINERS' => 'Diners brand', + 'HIPERCARD' => 'Hipercard brand', + 'AURA' => 'Aura brand', + 'ELO' => 'ELO brand', + 'PLENOCARD' => 'PlenoCard brand', + 'PERSONALCARD' => 'PersonalCard brand', + 'JCB' => 'JCB brand', + 'DISCOVER' => 'Discover brand', + 'BRASILCARD' => 'BrasilCard brand', + 'FORTBRASIL' => 'FortBrasil brand', + 'CARDBAN' => 'CardBAN brand', + 'VALECARD' => 'ValeCard brand', + 'CABAL' => 'Cabal brand', + 'MAIS' => 'MAIS brand', + 'AVISTA' => 'AVISTA brand', + 'GRANDCARD' => 'GrandCard brand', + 'SOROCRED' => 'Sorocred brand' + ); + + + /*** + * Get available list for accepted payment methods + * @return array + */ + public static function getAvailableKeysList() + { + return self::$availableNameList; + } + + /*** + * Check if a name is available for accepted payment methods. + * @param string $name + * @return boolean + */ + public static function isNameAvailable($name) + { + $key = strtoupper($name); + return (isset(self::$availableNameList[$key])); + } + + /*** + * Gets description by name + * @param string $name + * @return string + */ + public static function getDescriptionByName($name) + { + $key = strtoupper($name); + if (isset(self::$availableNameList[$key])) { + return self::$availableNameList[$key]; + } else { + return false; + } + } + + /*** + * Gets name key by description + * @param string $description + * @return string + */ + public static function getKeyByDescription($description) + { + return array_search(strtolower($description), array_map('strtolower', self::$availableNameList)); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethods.class.php b/PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethods.class.php new file mode 100644 index 0000000..d1701a2 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAcceptedPaymentMethods.class.php @@ -0,0 +1,71 @@ + 0) { + $this->setConfig($config); + } + } + + /** + * @param PagSeguroAcceptedPayments $acceptedPayments + */ + public function addConfig(PagSeguroAcceptedPayments $acceptedPayments) + { + $this->acceptedPaymentsList[] = $acceptedPayments; + } + + /** + * @param array $config + */ + public function setConfig(array $config) + { + $this->acceptedPaymentsList = $config; + } + + /** + * @return array + */ + public function getConfig() + { + if ($this->acceptedPaymentsList == null) { + $this->acceptedPaymentsList = array(); + } + return $this->acceptedPaymentsList; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAcceptedPayments.class.php b/PagSeguroLibrary/domain/PagSeguroAcceptedPayments.class.php new file mode 100644 index 0000000..949ed84 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAcceptedPayments.class.php @@ -0,0 +1,48 @@ +setEmail($email); + $this->setToken($token); + } else { + throw new Exception("Credentials not set."); + } + } + + /*** + * @return string the e-mail from this account credential object + */ + public function getEmail() + { + return $this->email; + } + + /*** + * Sets the e-mail from this account credential object + */ + public function setEmail($email) + { + $this->email = $email; + } + + /*** + * @return string the token from this account credential object + */ + public function getToken() + { + return $this->token; + } + + /*** + * Sets the token in this account credential object + */ + public function setToken($token) + { + $this->token = $token; + } + + /*** + * @return array a map of name value pairs that compose this set of credentials + */ + public function getAttributesMap() + { + return array( + 'email' => $this->email, + 'token' => $this->token + ); + } + + /*** + * @return string a string that represents the current object + */ + public function toString() + { + $credentials = array(); + $credentials['E-mail'] = $this->email; + $credentials['Token'] = $this->token; + return implode(' - ', $credentials); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAddress.class.php b/PagSeguroLibrary/domain/PagSeguroAddress.class.php new file mode 100644 index 0000000..52105db --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAddress.class.php @@ -0,0 +1,328 @@ + 'AC', + 'alagoas' => 'AL', + 'amapa' => 'AP', + 'amazonas' => 'AM', + 'bahia' => 'BA', + 'ceara' => 'CE', + 'espiritosanto' => 'ES', + 'goias' => 'GO', + 'maranhao' => 'MA', + 'matogrosso' => 'MT', + 'matogrossodosul' => 'MS', + 'matogrossosul' => 'MS', + 'minasgerais' => 'MG', + 'para' => 'PA', + 'paraiba' => 'PB', + 'parana' => 'PR', + 'pernambuco' => 'PE', + 'piaui' => 'PI', + 'riodejaneiro' => 'RJ', + 'riojaneiro' => 'RJ', + 'riograndedonorte' => 'RN', + 'riograndenorte' => 'RN', + 'riograndedosul' => 'RS', + 'riograndesul' => 'RS', + 'rondonia' => 'RO', + 'roraima' => 'RR', + 'santacatarina' => 'SC', + 'saopaulo' => 'SP', + 'sergipe' => 'SE', + 'tocantins' => 'TO', + 'distritofederal' => 'DF'); + + /*** + * Initializes a new instance of the Address class + * @param array $data + */ + public function __construct(array $data = null) + { + if (isset($data['postalCode'])) { + $this->postalCode = $data['postalCode']; + } + if (isset($data['street'])) { + $this->street = $data['street']; + } + if (isset($data['number'])) { + $this->number = $data['number']; + } + if (isset($data['complement'])) { + $this->complement = $data['complement']; + } + if (isset($data['district'])) { + $this->district = $data['district']; + } + if (isset($data['city'])) { + $this->city = $data['city']; + } + if (isset($data['state'])) { + $this->state = $data['state']; + } + if (isset($data['country'])) { + $this->country = $data['country']; + } + } + + /*** + * @return string the street + */ + public function getStreet() + { + return $this->street; + } + + /*** + * @return string the number + */ + public function getNumber() + { + return $this->number; + } + + /*** + * @return string the complement + */ + public function getComplement() + { + return $this->complement; + } + + /*** + * @return string the distrcit + */ + public function getDistrict() + { + return $this->district; + } + + /*** + * @return string the city + */ + public function getCity() + { + return $this->city; + } + + /*** + * @return string the state + */ + public function getState() + { + return $this->state; + } + + /*** + * @return string the postal code + */ + public function getPostalCode() + { + return $this->postalCode; + } + + /*** + * @return string the country + */ + public function getCountry() + { + return $this->country; + } + + /*** + * Sets the country + * @param String $country + */ + public function setCountry($country) + { + $this->country = $country; + } + + /*** + * Sets the street + * @param String $street + */ + public function setStreet($street) + { + $this->street = $street; + } + + /*** + * sets the numbetr + * @param String $number + */ + public function setNumber($number) + { + $this->number = $number; + } + + /*** + * Sets the complement + * @param String $complement + */ + public function setComplement($complement) + { + $this->complement = $complement; + } + + /*** + * sets the district + * @param String $district + */ + public function setDistrict($district) + { + $this->district = $district; + } + + /*** + * Sets the city + * @param String $city + */ + public function setCity($city) + { + $this->city = $city; + } + + /*** + * Sets the state + * @param String $state + */ + public function setState($state) + { + $this->state = $this->treatState($state); + } + + /*** + * Sets the postal code + * @param String $postalCode + */ + public function setPostalCode($postalCode) + { + $this->postalCode = $postalCode; + } + + /*** + * Handle the state to pass in format expected in PagSeguro + * @param type $defaultState + * @return string + */ + private function treatState($defaultState) + { + + if (strlen($defaultState) == 2) { + foreach (self::$acronyms as $key => $val) { + if ($val == strtoupper($defaultState)) { + return strtoupper($defaultState); + } + } + return ''; + } + + $state = utf8_decode($defaultState); + $state = strtolower($state); + + // Code ASCII of the vowel + $ascii['a'] = range(224, 230); + $ascii['e'] = range(232, 235); + $ascii['i'] = range(236, 239); + $ascii['o'] = array_merge(range(242, 246), array(240, 248)); + $ascii['u'] = range(249, 252); + + // Code ASCII of the others character + $ascii['b'] = array(223); + $ascii['c'] = array(231); + $ascii['d'] = array(208); + $ascii['n'] = array(241); + $ascii['y'] = array(253, 255); + + foreach ($ascii as $key => $item) { + $accents = ''; + foreach ($item as $code) { + $accents .= chr($code); + } + $change[$key] = '/[' . $accents . ']/i'; + } + + $state = preg_replace(array_values($change), array_keys($change), $state); + + $state = preg_replace("/\s/", "", $state); + + foreach (self::$acronyms as $key => $val) { + if ($key == $state) { + $acronym = $val; + return $acronym; + } + } + + return ''; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroApplicationCredentials.class.php b/PagSeguroLibrary/domain/PagSeguroApplicationCredentials.class.php new file mode 100644 index 0000000..96e8367 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroApplicationCredentials.class.php @@ -0,0 +1,144 @@ +setAppId($appId); + $this->setAppKey($appKey); + } else { + throw new Exception("Authorization credentials not set."); + } + + if ($authorizationCode !== null) { + $this->setAuthorizationCode($authorizationCode); + } + + } + + /*** + * @return string the appID from this authorization credentials + */ + public function getAppId() + { + return $this->appId; + } + + /*** + * Sets the app ID from this authorization credentials + * @param string $appId + */ + public function setAppId($appId) + { + $this->appId = $appId; + } + + /*** + * @return string the appKey from this authorization credentials + */ + public function getAppKey() + { + return $this->appKey; + } + + /*** + * Sets the app ID from this authorization credentials + * @param string $appKey + */ + public function setAppKey($appKey) + { + $this->appKey = $appKey; + } + + /*** + * @return string the appKey from this authorization credentials + */ + public function getAuthorizationCode() + { + return $this->authorizationCode; + } + + /*** + * Sets the app ID from this authorization credentials + * @param string $authorizationCode + */ + public function setAuthorizationCode($authorizationCode) + { + $this->authorizationCode = $authorizationCode; + } + + /*** + * @return array a map of name value pairs that compose this set of credentials + */ + public function getAttributesMap() + { + return array( + 'appId' => $this->appId, + 'appKey' => $this->appKey, + 'authorizationCode' => $this->authorizationCode + ); + } + + /*** + * @return string a string that represents the current object + */ + public function toString() + { + $credentials = array(); + $credentials['AppID'] = $this->appId; + $credentials['AppKey'] = $this->appKey; + $credentials['AuthorizationCode'] = $this->appKey; + return implode(' - ', $credentials); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAuthorization.class.php b/PagSeguroLibrary/domain/PagSeguroAuthorization.class.php new file mode 100644 index 0000000..7000de8 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAuthorization.class.php @@ -0,0 +1,191 @@ +code; + } + + /*** + * Sets the authorization code + * @param string $code + */ + public function setCode($code) + { + if (isset($code)) { + $this->code = $code; + } + } + + /*** + * @return string of authorization date. + */ + public function getDate() + { + return $this->date; + } + + /*** + * Sets the authorization date + * @param string $date + */ + public function setDate($date) + { + if (isset($date)) { + $this->date = $date; + } + } + + /*** + * @return string of authorization creation date. + */ + public function getCreationDate() + { + return $this->creationDate; + } + + /*** + * Sets the authorization creation date + * @param string $creationDate + */ + public function setCreationDate($creationDate) + { + if (isset($creationDate)) { + $this->creationDate = $creationDate; + } + } + + /*** + * @return string of authorization reference. + */ + public function getReference() + { + return $this->reference; + } + + /*** + * Sets the authorization reference + * @param string $reference + */ + public function setReference($reference) + { + if (isset($reference)) { + $this->reference = $reference; + } + } + + /*** + * @return string of authorization permissions. + */ + public function getPermissions() + { + return $this->permissions; + } + + /*** + * Sets the authorization permissions + * @param string $permissions + */ + public function setPermissions($permissions) + { + if (isset($permissions)) { + $this->permissions = $permissions; + } + } + + /*** + * @return string of authorization account. + */ + public function getAccount() + { + return $this->account; + } + + /*** + * Sets the authorization account + * @param string $account + */ + public function setAccount($account) + { + if (isset($account)) { + $this->account = $account; + } + } + + /*** + * @return String that resents the current object + */ + public function toString() + { + $authorization = array(); + $authorization['code'] = $this->code; + $authorization['reference'] = $this->reference; + return "Authorization: " . implode(' - ', $authorization); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAuthorizationAccount.class.php b/PagSeguroLibrary/domain/PagSeguroAuthorizationAccount.class.php new file mode 100644 index 0000000..8e8f7c5 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAuthorizationAccount.class.php @@ -0,0 +1,67 @@ +setPublicKey($account); + } else { + throw new Exception("Wasn't possible construct the account"); + } + } + + /*** + * @return string of public key + */ + public function getPublicKey() + { + return $this->publicKey; + } + + /*** + * Sets the authorization account public key + * @param string $value + */ + public function setPublicKey($value) + { + if (isset($value)) { + $this->publicKey = $value; + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAuthorizationPermission.class.php b/PagSeguroLibrary/domain/PagSeguroAuthorizationPermission.class.php new file mode 100644 index 0000000..c3ff359 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAuthorizationPermission.class.php @@ -0,0 +1,117 @@ +setCode($code); + $this->setStatus($status); + $this->setLastUpdate($lastUpdate); + } else { + throw new Exception("Wasn't possible construct the permission"); + } + } + + /*** + * @return string of authorization permission code + */ + public function getCode() + { + return $this->code; + } + + /*** + * Sets the authorization permission code + * @param mixed $code + */ + public function setCode($code) + { + if (isset($code)) { + $this->code = $code; + } + } + + /*** + * @return string of authorization permission status + */ + public function getStatus() + { + return $this->status; + } + + /*** + * Sets the authorization permission status + * @param string $status + */ + public function setStatus($status) + { + if (isset($status)) { + $this->status = $status; + } + } + + /*** + * @return string of authorization last update + */ + public function getLastUpdate() + { + return $this->lastUpdate; + } + + /*** + * Sets the authorization permission last update + * @param date $lastUpdate + */ + public function setLastUpdate($lastUpdate) + { + if (isset($lastUpdate)) { + $this->lastUpdate = $lastUpdate; + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAuthorizationPermissions.class.php b/PagSeguroLibrary/domain/PagSeguroAuthorizationPermissions.class.php new file mode 100644 index 0000000..73fcf17 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAuthorizationPermissions.class.php @@ -0,0 +1,77 @@ +setPermissions($permissions); + } + } + + /*** + * @return array of permissions + */ + public function getPermissions() + { + return $this->permissions; + } + + /*** + * @param array $permissions + */ + public function setPermissions($permissions) + { + if (isset($permissions)) { + $this->permissions = $permissions; + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAuthorizationRequest.class.php b/PagSeguroLibrary/domain/PagSeguroAuthorizationRequest.class.php new file mode 100644 index 0000000..2b72767 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAuthorizationRequest.class.php @@ -0,0 +1,226 @@ +reference = $reference; + } + /*** + * @return string of $redirectURL + */ + public function getReference() + { + return $this->reference; + } + + /*** + * Sets redirect URL for PagSeguro authorization requests + * @param string $redirectURL + */ + public function setRedirectURL($redirectURL) + { + $this->redirectURL = $redirectURL; + } + /*** + * @return string of $redirectURL + */ + public function getRedirectURL() + { + return $this->redirectURL; + } + + /*** + * Sets notificationURL for PagSeguro authorization requests + * @param string $notificationURL + */ + public function setNotificationURL($notificationURL) + { + $this->permissions = $notificationURL; + } + + /*** + * @return string of notificationURL + */ + public function getNotificationURL() + { + return $this->notificationURL; + } + + /*** + * @return array of permissions + */ + public function getPermissions() + { + return $this->permissions; + } + + /*** + * Sets permissions for PagSeguro authorization requests + * @param array $permissions + */ + public function setPermissions(array $permissions) + { + $this->permissions = new PagSeguroAuthorizationPermissions($permissions); + } + + /*** + * Sets parameter for PagSeguro authorization requests + * + * @param PagSeguroParameter $parameter + */ + public function setParameter($parameter) + { + $this->parameter = $parameter; + } + + /*** + * Gets parameter for PagSeguro authorization requests + * + * @return PagSeguroParameter + */ + public function getParameter() + { + if ($this->parameter == null) { + $this->parameter = new PagSeguroParameter(); + } + return $this->parameter; + } + + /*** + * add a parameter for PagSeguro authorization request + * + * @param PagSeguroParameterItem $parameterName key + * @param PagSeguroParameterItem $parameterValue value + */ + public function addParameter($parameterName, $parameterValue) + { + $this->getParameter()->addItem(new PagSeguroParameterItem($parameterName, $parameterValue)); + } + + /*** + * add a parameter for PagSeguro authorization request + * + * @param PagSeguroParameterItem $parameterName key + * @param PagSeguroParameterItem $parameterValue value + * @param PagSeguroParameterItem $parameterIndex group + */ + public function addIndexedParameter($parameterName, $parameterValue, $parameterIndex) + { + $this->getParameter()->addItem(new PagSeguroParameterItem($parameterName, $parameterValue, $parameterIndex)); + } + + /*** + * Calls the PagSeguro web service and register this request for authorization + * @param PagSeguroCredentials $credentials + * @param bool $onlyAuthorizationCode + * @return PagSeguroAuthorizationService Data + */ + public function register(PagSeguroCredentials $credentials, $onlyAuthorizationCode = false) + { + return PagSeguroAuthorizationService::createAuthorizationRequest($credentials, $this, $onlyAuthorizationCode); + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + + $request = array(); + $request['Reference'] = $this->reference; + + return "PagSeguroAuthorizationRequest: " . implode(' - ', $request); + } + + /*** + * Verify if the adress of NotificationURL or RedirectURL is for tests and return empty + * @param type $url + * @return type + */ + public function verifyURLTest($url) + { + $address = array('127.0.0.1','::1'); + + foreach ($address as $item) { + $find = strpos($url, $item); + + if ($find) { + return false; + } else { + return $url; + } + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroAuthorizationSearchResult.class.php b/PagSeguroLibrary/domain/PagSeguroAuthorizationSearchResult.class.php new file mode 100644 index 0000000..8cea536 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroAuthorizationSearchResult.class.php @@ -0,0 +1,158 @@ +currentPage; + } + + /*** + * Sets the current page number + * @param integer $currentPage + */ + public function setCurrentPage($currentPage) + { + $this->currentPage = $currentPage; + } + + /*** + * @return the date/time when this search was executed + */ + public function getDate() + { + return $this->date; + } + + /*** + * Set the date/time when this search was executed + * @param date + */ + public function setDate($date) + { + $this->date = $date; + } + + /*** + * @return the number of authorizations summaries in the current page + */ + public function getResultsInThisPage() + { + return $this->resultsInThisPage; + } + + /*** + * Sets the number of authorizations summaries in the current page + * + * @param resultsInThisPage + */ + public function setResultsInThisPage($resultsInThisPage) + { + $this->resultsInThisPage = $resultsInThisPage; + } + + /*** + * @return the total number of pages + */ + public function getTotalPages() + { + return $this->totalPages; + } + + /*** + * Sets the total number of pages + * + * @param totalPages + */ + public function setTotalPages($totalPages) + { + $this->totalPages = $totalPages; + } + + /*** + * @return PagSeguroAuthorizations the authorizations summaries in this page + * @see PagSeguroAuthorizations + */ + public function getAuthorizations() + { + return $this->authorizations; + } + + /*** + * Sets the authorizations summaries in this page + * @param PagSeguroAuthorization $authorizations + */ + public function setAuthorizations($authorizations) + { + $this->authorizations = $authorizations; + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + $authorizations = array(); + + $authorizations['Date'] = $this->date; + $authorizations['CurrentPage'] = $this->currentPage; + $authorizations['TotalPages'] = $this->totalPages; + $authorizations['Transactions in this page'] = $this->resultsInThisPage; + + return "PagSeguroAuthorizationsSearchResult: " . implode(' - ', $authorizations); + + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroBilling.class.php b/PagSeguroLibrary/domain/PagSeguroBilling.class.php new file mode 100644 index 0000000..a768843 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroBilling.class.php @@ -0,0 +1,67 @@ +setAddress(new PagSeguroAddress($data)); + } elseif ($data instanceof PagSeguroAddress) { + $this->setAddress($data); + } + } + + /*** + * Sets the billing address + * @see PagSeguroAddress + * @param PagSeguroAddress $address + */ + public function setAddress(PagSeguroAddress $address) + { + $this->address = $address; + } + + /*** + * @return PagSeguroAddress the billing address + * @see PagSeguroAddress + */ + public function getAddress() + { + return $this->address; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroCredentials.class.php b/PagSeguroLibrary/domain/PagSeguroCredentials.class.php new file mode 100644 index 0000000..cf536a9 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroCredentials.class.php @@ -0,0 +1,39 @@ +setNumber($data['number']); + } + if (isset($data['cvv'])) { + $this->setCvv($data['cvv']); + } + if (isset($data['expirationMonth'])) { + $this->setExpirationMonth($data['expirationMonth']); + } + if (isset($data['expirationYear'])) { + $this->setExpirationYear($data['expirationYear']); + } + } + } + + /*** + * Sets the card number + * @param int $number + */ + public function setNumber($number) + { + $this->number = $number; + } + + /*** + * @return int the card number + */ + public function getNumber() + { + return $this->number; + } + + /*** + * Sets the card cvv + * @param int $cvv + */ + public function setCvv($cvv) + { + $this->cvv = $cvv; + } + + /*** + * @return int the card cvv + */ + public function getCvv() + { + return $this->cvv; + } + + /*** + * Sets the card expirationMonth + * @param int $expirationMonth + */ + public function setExpirationMonth($expirationMonth) + { + $this->expirationMonth = $expirationMonth; + } + + /*** + * @return int expirationMonth from credit card + */ + public function getExpirationMonth() + { + return $this->expirationMonth; + } + + /*** + * Sets the card expirationYear + * @param int $expirationYear + */ + public function setExpirationYear($expirationYear) + { + $this->expirationYear = $expirationYear; + } + + /*** + * @return int expirationYear from credit card + */ + public function getExpirationYear() + { + return $this->expirationYear; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroCreditCardCheckout.class.php b/PagSeguroLibrary/domain/PagSeguroCreditCardCheckout.class.php new file mode 100644 index 0000000..03226fd --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroCreditCardCheckout.class.php @@ -0,0 +1,170 @@ +setBrand($data['brand']); + } + if (isset($data['token'])) { + $this->setToken($data['token']); + } + if (isset($data['holder'])) { + $this->setHolder($data['holder']); + } + if (isset($data['installment'])) { + $this->setInstallment($data['installment']); + } + if (isset($data['billing'])) { + $this->setBilling($data['billing']); + } + } + } + + /*** + * Sets the credit card brand + * @param string $brand + */ + public function setBrand($brand) + { + $this->brand = $brand; + } + + /*** + * @return string the credit card brand + */ + public function getBrand() + { + return $this->brand; + } + + /*** + * Sets the credit card token + * @param mixed $token + */ + public function setToken($token) + { + $this->token = $token; + } + + /*** + * @return mixed the credit card token + */ + public function getToken() + { + return $this->token; + } + + /*** + * Sets the PagSeguroCreditCardHolder + * @param intanceof PagSeguroCreditCardHolder $holder + */ + public function setHolder($holder) + { + $this->holder = $holder; + } + + /*** + * @return PagSeguroCreditCardHolder object + * @see PagSeguroCreditCardHolder + */ + public function getHolder() + { + return $this->holder; + } + + /*** + * Sets the PagSeguroInstallment + * @param intanceof PagSeguroInstallment $installment + */ + public function setInstallment($installment) + { + $this->installment = $installment; + } + + /*** + * @return PagSeguroInstallment object + * @see PagSeguroInstallment + */ + public function getInstallment() + { + return $this->installment; + } + + /*** + * Sets the PagSeguroBilling + * @param intanceof PagSeguroBilling $billing + */ + public function setBilling($billing) + { + $this->billing = $billing; + } + + /*** + * @return PagSeguroBilling object + * @see PagSeguroBilling + */ + public function getBilling() + { + return $this->billing; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroCreditCardHolder.class.php b/PagSeguroLibrary/domain/PagSeguroCreditCardHolder.class.php new file mode 100644 index 0000000..f22bc87 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroCreditCardHolder.class.php @@ -0,0 +1,180 @@ +setName($data['name']); + } + if (isset($data['documents']) && is_array($data['documents'])) { + $this->setDocuments($data['documents']); + } elseif (isset($data['documents']) && $data['documents'] instanceof PagSeguroDocument) { + $this->documents = $data['documents']; + } + if (isset($data['birthDate'])) { + $this->setBirthDate($data['birthDate']); + } + if (isset($data['phone']) && $data['phone'] instanceof PagSeguroPhone) { + $this->setPhone($data['phone']); + } else if (isset($data['areaCode']) && isset($data['number'])) { + $this->setPhone($data['areaCode'], $data['number']); + } + } + } + + /*** + * Set the credit card holder name + * @param $name string + */ + public function setName($name) + { + $this->name = $name; + } + + /*** + * @return string the credit card holder name + */ + public function getName() + { + return $this->name; + } + + /*** + * Set PagSeguro documents + * @param array $documents + * @see PagSeguroDocument + */ + public function setDocuments(array $documents) + { + if ($documents instanceof PagSeguroDocument) { + $this->documents = $documents; + } else { + if (is_array($documents)) { + $this->addDocument($documents['type'], $documents['value']); + } + } + } + + /*** + * Add a document for Holder object + * @param String $type + * @param String $value + */ + public function addDocument($type, $value) + { + if ($type && $value) { + if (count($this->documents) == 0) { + $data = array( + 'type' => $type, + 'value' => $value + ); + $document = new PagSeguroDocument($data); + $this->documents = $document; + } + } + } + + /*** + * Get Holder documents + * @return array PagSeguroDocument List of PagSeguroDocument + * @see PagSeguroDocument + */ + public function getDocuments() + { + return $this->documents; + } + + /*** + * Set the credit card holder birth date + * @param $birthDate date + */ + public function setBirthDate($birthDate) + { + $this->birthDate = $birthDate; + } + + /*** + * @return date the credit card holder birth date + */ + public function getBirthDate() + { + return $this->birthDate; + } + + /*** + * Sets the holder phone + * @param String $areaCode + * @param String $number + */ + public function setPhone($areaCode, $number = null) + { + $param = $areaCode; + if ($param instanceof PagSeguroPhone) { + $this->phone = $param; + } elseif ($number) { + $phone = new PagSeguroPhone($areaCode, $number); + $this->phone = $phone; + } + } + + /*** + * @return PagSeguroPhone the holder phone + * @see PagSeguroPhone + */ + public function getPhone() + { + return $this->phone; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroCurrencies.class.php b/PagSeguroLibrary/domain/PagSeguroCurrencies.class.php new file mode 100644 index 0000000..a2c5a46 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroCurrencies.class.php @@ -0,0 +1,101 @@ + + * key = currency name + * value = currency iso code 3 + * + * @var array + */ + private static $currencies = array( + 'REAL' => 'BRL' + ); + + /*** + * Check if currency is available by informed iso code for PagSeguro transactions + * @param string $currency_iso_code + * @return boolean + */ + public static function checkCurrencyAvailabilityByIsoCode($currency_iso_code) + { + $available = false; + if (array_search(strtoupper($currency_iso_code), self::$currencies)) { + $available = true; + } + return $available; + } + + /*** + * Check if currency is available by informed currency name for PagSeguro transactions + * @param string $name + * @return boolean + */ + public static function checkCurrencyAvailabilityByName($name) + { + $available = false; + if (array_key_exists(strtoupper($name), self::$currencies)) { + $available = true; + } + return $available; + } + + /*** + * Return currencies list + * @return array + */ + public static function getCurrenciesList() + { + return self::$currencies; + } + + /*** + * Return iso code by currency name + * Default return BRL (Brazilian Real) iso code + * @param string $name - the currency name + * @return string + */ + public static function getIsoCodeByName($name) + { + $name = strtoupper($name); + return (isset(self::$currencies[$name])) ? self::$currencies[$name] : self::$currencies['REAL']; + } + + /** + * Return currency name by iso code + * @param string $iso_code + * @return string + */ + public static function getCurrencyNameByIsoCode($iso_code) + { + return array_search(strtoupper($iso_code), self::getCurrenciesList()); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroDirectPaymentMethods.class.php b/PagSeguroLibrary/domain/PagSeguroDirectPaymentMethods.class.php new file mode 100644 index 0000000..e2ea2b6 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroDirectPaymentMethods.class.php @@ -0,0 +1,78 @@ + "creditCard", + "BOLETO" => "boleto", + "EFT" => "eft" + ); + + /* + * @var $paymentMethod + */ + private $paymentMethod; + + /*** + * Initializes a new instance of the PaymentMethods class + * @param $paymentMethod + */ + public function __construct($paymentMethod = null) + { + if (isset($paymentMethod)) { + if (array_key_exists($paymentMethod, $this->methodsList)) { + $this->setPaymentMethod($this->methodsList[$paymentMethod]); + } else { + throw new Exception("Direct payment method not found"); + } + } + } + + /*** + * @return the method + */ + public function getPaymentMethod() + { + return $this->paymentMethod; + } + + /*** + * Sets the payment method + * @param $paymentMethod + */ + public function setPaymentMethod($paymentMethod) + { + if (isset($paymentMethod)) { + $this->paymentMethod = $paymentMethod; + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroDirectPaymentRequest.class.php b/PagSeguroLibrary/domain/PagSeguroDirectPaymentRequest.class.php new file mode 100644 index 0000000..c895601 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroDirectPaymentRequest.class.php @@ -0,0 +1,292 @@ +senderHash; + } + + /*** + * Sets the sender hash + * @param string $senderHash + */ + public function setSenderHash($senderHash) + { + $this->senderHash = $senderHash; + } + + /*** + * @return string the receiverEmail + */ + public function getReceiverEmail() + { + return $this->receiverEmail; + } + + /*** + * Sets the receiver email + * @param string $receiverEmail + */ + public function setReceiverEmail($receiverEmail) + { + $this->receiverEmail = $receiverEmail; + } + + /*** + * @return String payment mode for this payment request + */ + public function getPaymentMode() + { + return $this->paymentMode; + } + + /*** + * Sets payment mode for this payment request + * @param string|object $mode + */ + public function setPaymentMode($mode) + { + + try { + if ($mode instanceof PagSeguroPaymentMode) { + $this->paymentMode = $mode; + } else { + $this->paymentMode = new PagSeguroPaymentMode($mode); + } + } catch (Exception $e) { + die($e->getMessage()); + } + } + + /*** + * @return PagSeguroPaymentMethod payment method for this payment request + */ + public function getPaymentMethod() + { + return $this->paymentMethod; + } + + /*** + * Sets payment method for this payment request + * @param string|object $method + */ + public function setPaymentMethod($method) + { + try { + if ($method instanceof PagSeguroDirectPaymentMethods) { + $this->paymentMethod = $method; + } else { + $this->paymentMethod = new PagSeguroDirectPaymentMethods($method); + } + } catch (Exception $e) { + die($e->getMessage()); + } + } + + /*** + * Sets the billing address for this payment request + * @param String $postalCode + * @param String $street + * @param String $number + * @param String $complement + * @param String $district + * @param String $city + * @param String $state + * @param String $country + */ + public function setBillingAdress( + $postalCode, + $street = null, + $number = null, + $complement = null, + $district = null, + $city = null, + $state = null, + $country = null + ) { + + $param = $postalCode; + $this->billing = new PagSeguroBilling(); + if (isset($param) and is_array($param)) { + $this->billing->setAddress(new PagSeguroAddress($param)); + } elseif ($param instanceof PagSeguroAddress) { + $this->billing->setAddress($param); + } else { + $billindAdress = array( + 'postalCode' => $postalCode, + 'street' => $street, + 'number' => $number, + 'complement' => $complement, + 'district' => $district, + 'city' => $city, + 'state' => $state, + 'country' => $country + ); + + $this->billing->setAddress(new PagSeguroAddress($billindAdress)); + } + } + + /*** + * @return PagSeguroBilling the billing information for this payment request + * @see PagSeguroBilling + */ + public function getBillingAdress() + { + return $this->billing; + } + + /*** + * Sets the info for credit card for this payment request + * @param array|object $params + */ + public function setCreditCard($params = null) + { + + if ($params instanceof PagSeguroCreditCardCheckout) { + $this->creditCard = $params; + } elseif (isset($params) && is_array($params)) { + $this->creditCard = new PagSeguroCreditCardCheckout(); + if (isset($params['token'])) { + $this->creditCard->setToken($params['token']); + } + if (isset($params['installment']) && $params['installment'] instanceof PagSeguroInstallment) { + $this->creditCard->setInstallment($params['installment']); + } + if (isset($params['holder']) && $params['holder'] instanceof PagSeguroCreditCardHolder) { + $this->creditCard->setHolder($params['holder']); + } + if (isset($params['billing']) && $params['billing'] instanceof PagSeguroBilling) { + $this->creditCard->setBilling($params['billing']); + } + } + } + + /*** + * @return PagSeguroCreditCard the credit card info + * @see PagSeguroCreditCard + */ + public function getCreditCard() + { + return $this->creditCard; + } + + /*** + * @return string the bank name of this payment request for online debit + */ + public function getOnlineDebit() + { + return $this->onlineDebit; + } + + /*** + * Sets the bank name of this payment request for online debit + * @param string|object $bankName + */ + public function setOnlineDebit($bankName) + { + + if ($bankName instanceof PagSeguroOnlineDebitCheckout) { + $this->onlineDebit = $bankName; + } elseif (is_array($bankName)) { + $this->onlineDebit = new PagSeguroOnlineDebitCheckout($bankName); + } else { + $this->onlineDebit = new PagSeguroOnlineDebitCheckout( + array( + "bankName" => $bankName + ) + ); + } + } + + /*** + * Calls the PagSeguro web service and register this request for payment + * + * @param PagSeguroCredentials $credentials + * @return String The URL to where the user needs to be redirected to in order to complete the payment process + */ + public function register(PagSeguroCredentials $credentials) + { + return PagSeguroDirectPaymentService::checkoutRequest($credentials, $this); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroDocument.class.php b/PagSeguroLibrary/domain/PagSeguroDocument.class.php new file mode 100644 index 0000000..bac0ecc --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroDocument.class.php @@ -0,0 +1,102 @@ + 'CPF', + 2 => 'CNPJ' + ); + + /*** + * The type of document + * @var string + */ + private $type; + + /*** + * The value of document + * @var string + */ + private $value; + + public function __construct(array $data = null) + { + if ($data) { + if (isset($data['type']) && isset($data['value'])) { + $this->setType($data['type']); + $this->setValue(PagSeguroHelper::getOnlyNumbers($data['value'])); + } + } + } + + /*** + * Get document type + * @return String + */ + public function getType() + { + return $this->type; + } + + /*** + * Set document type + * @param String $type + */ + public function setType($type) + { + $this->type = strtoupper($type); + } + + /*** + * Get document value + * @return String + */ + public function getValue() + { + return $this->value; + } + + /*** + * Set document value + * @param String $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /*** + * Check if document type is available for PagSeguro + * @param string $documentType + * @return array|boolean + */ + public static function isDocumentTypeAvailable($documentType) + { + return (array_search(strtoupper($documentType), self::$availableDocumentList)); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroDocuments.class.php b/PagSeguroLibrary/domain/PagSeguroDocuments.class.php new file mode 100644 index 0000000..2509a72 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroDocuments.class.php @@ -0,0 +1,83 @@ + 'Cadastro de Pessoa Física', + 'CNPJ' => 'Cadastro de Pessoa Jurídica' + ); + + /*** + * Get available document list for Sender use in PagSeguro transactions + * @return array + */ + public static function getAvailableDocumentList() + { + return self::$availableDocumentList; + } + + /*** + * Check if document type is available for PagSeguro + * @param string $documentType + * @return boolean + */ + public static function isDocumentTypeAvailable($documentType) + { + $documentType = strtoupper($documentType); + return (isset(self::$availableDocumentList[$documentType])); + } + + /*** + * Gets document description by type + * @param string + * @return string + */ + public static function getDocumentByType($documentType) + { + $documentType = strtoupper($documentType); + if (isset(self::$availableDocumentList[$documentType])) { + return self::$availableDocumentList[$documentType]; + } else { + return false; + } + } + + /*** + * Gets document type by description + * @param string $documentDescription + * @return string + */ + public static function getDocumentByDescription($documentDescription) + { + return array_search(strtolower($documentDescription), array_map('strtolower', self::$availableDocumentList)); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroError.class.php b/PagSeguroLibrary/domain/PagSeguroError.class.php new file mode 100644 index 0000000..9e5edcf --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroError.class.php @@ -0,0 +1,86 @@ +setCode($code); + $this->setMessage($message); + } + + /*** + * @return integer|string the code + */ + public function getCode() + { + return $this->code; + } + + /*** + * Sets the code + * @param String $code + */ + public function setCode($code) + { + $this->code = $code; + } + + /*** + * @return String the error description + */ + public function getMessage() + { + return $this->message; + } + + /*** + * Sets the error description + * @param String $message + */ + public function setMessage($message) + { + $this->message = $message; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroExcludePaymentMethod.class.php b/PagSeguroLibrary/domain/PagSeguroExcludePaymentMethod.class.php new file mode 100644 index 0000000..855089d --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroExcludePaymentMethod.class.php @@ -0,0 +1,83 @@ +setName($name); + } + if (isset($group) && !PagSeguroHelper::isEmpty($group)) { + $this->setGroup($group); + } + } + + /** + * @return mixed + */ + public function getName() + { + return $this->name; + } + + /** + * @param $name + */ + public function setName($name) + { + $this->name = $name; + } + + /** + * @return mixed + */ + public function getGroup() + { + return $this->group; + } + + /** + * @param $group + */ + public function setGroup($group) + { + $this->group = $group; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroHttpStatus.class.php b/PagSeguroLibrary/domain/PagSeguroHttpStatus.class.php new file mode 100644 index 0000000..42c123a --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroHttpStatus.class.php @@ -0,0 +1,90 @@ + 'OK', + 400 => 'BAD_REQUEST', + 401 => 'UNAUTHORIZED', + 403 => 'FORBIDDEN', + 404 => 'NOT_FOUND', + 500 => 'INTERNAL_SERVER_ERROR', + 502 => 'BAD_GATEWAY' + ); + /*** + * @var int + */ + private $status; + /*** + * @var bool + */ + private $type; + + /*** + * @param $status + */ + public function __construct($status) + { + if ($status) { + $this->status = (int) $status; + $this->type = $this->getTypeByStatus($this->status); + } + } + + /*** + * @return bool + */ + public function getType() + { + return $this->type; + } + + /*** + * @return int + */ + public function getStatus() + { + return $this->status; + } + + /*** + * @param $status + * @return bool + */ + private function getTypeByStatus($status) + { + if (isset($this->typeList[(int) $status])) { + return $this->typeList[(int) $status]; + } else { + return false; + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroInstallment.class.php b/PagSeguroLibrary/domain/PagSeguroInstallment.class.php new file mode 100644 index 0000000..fef0ad9 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroInstallment.class.php @@ -0,0 +1,103 @@ +setQuantity($data['quantity']); + } + if (isset($data['value'])) { + $this->setValue($data['value']); + } + } + } + + /*** + * Set installment quantity + * @param $quantity int + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + } + + /*** + * @return int installment quantity + */ + public function getQuantity() + { + return $this->quantity; + } + + /*** + * Set installment value + * @param $value float + */ + public function setValue($value) + { + $this->value = $value; + } + + /*** + * @return float installment value + */ + public function getValue() + { + return $this->value; + } + + /*** + * Sets the installment value and quantity + * @param $quantity int + * @param $value float + */ + public function setInstallment($quantity, $value = null) + { + $param = $quantity; + if (isset($param) && is_array($param) || is_object($param)) { + $this->quantity = $param['quantity']; + $this->value = $param['value']; + } else { + $this->quantity = $quantity; + $this->value = $value; + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroInstallments.class.php b/PagSeguroLibrary/domain/PagSeguroInstallments.class.php new file mode 100644 index 0000000..5f65fcd --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroInstallments.class.php @@ -0,0 +1,219 @@ +setInstallment($param); + } else { + $this->setInstallment( + $cardBrand, + $quantity, + $amount, + $totalAmount, + $interestFree + ); + } + } + + /*** + * Set brand of credit card + * @param $cardBrand string + */ + public function setCardBrand($cardBrand) + { + $this->cardBrand = $cardBrand; + } + + /*** + * @return string the credit card brand + */ + public function getCardBrand() + { + return $this->cardBrand; + } + + /*** + * Set the installments quantity + * @param $quantity int + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + } + + /*** + * @return int of installments quantity + */ + public function getQuantity() + { + return $this->quantity; + } + + /*** + * Set the installments amount + * @param $installmentAmount float + */ + public function setInstallmentAmount($installmentAmount) + { + $this->installmentAmount = $installmentAmount; + } + + /*** + * @return float of installments amount + */ + public function getInstallmentAmount() + { + return $this->installmentAmount; + } + + /*** + * Set the installments total amount + * @param $totalAmount float + */ + public function setTotalAmount($totalAmount) + { + $this->totalAmount = $totalAmount; + } + + /*** + * @return float of installments total amount + */ + public function getTotalAmount() + { + return $this->totalAmount; + } + + /*** + * Set the installments interest free + * @param $interestFree float + */ + public function setInterestFree($interestFree) + { + $this->interestFree = $interestFree; + } + + /*** + * @return float of installments interest free + */ + public function getInterestFree() + { + return $this->interestFree; + } + + /*** + * Set the installments + * @param array|string $cardBrand + * @param int $quantity + * @param float $amount + * @param float $totalAmount + * @param float $interestFree + */ + public function setInstallment( + $cardBrand, + $quantity = null, + $amount = null, + $totalAmount = null, + $interestFree = null + ) { + $param = $cardBrand; + if (isset($param) && is_array($param) || is_object($param)) { + if (isset($param->cardBrand)) { + $this->setCardBrand($param->cardBrand); + } + if (isset($param->quantity)) { + $this->setQuantity($param->quantity); + } + if (isset($param->installmentAmount)) { + $this->setInstallmentAmount($param->installmentAmount); + } + if (isset($param->totalAmount)) { + $this->setTotalAmount($param->totalAmount); + } + if (isset($param->interestFree)) { + $this->setInterestFree($param->interestFree); + } + } else { + if (isset($cardBrand)) { + $this->setCardBrand($cardBrand); + } + if (isset($quantity)) { + $this->setQuantity($quantity); + } + if (isset($amount)) { + $this->setInstallmentAmount($amount); + } + if (isset($totalAmount)) { + $this->setTotalAmount($totalAmount); + } + if (isset($interestFree)) { + $this->setInterestFree($interestFree); + } + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroItem.class.php b/PagSeguroLibrary/domain/PagSeguroItem.class.php new file mode 100644 index 0000000..f1c8c13 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroItem.class.php @@ -0,0 +1,190 @@ +setId($data['id']); + } + if (isset($data['description'])) { + $this->setDescription($data['description']); + } + if (isset($data['quantity'])) { + $this->setQuantity($data['quantity']); + } + if (isset($data['amount'])) { + $this->setAmount($data['amount']); + } + if (isset($data['weight'])) { + $this->setWeight($data['weight']); + } + if (isset($data['shippingCost'])) { + $this->setShippingCost($data['shippingCost']); + } + } + } + + /*** + * @return integer the product identifier + */ + public function getId() + { + return $this->id; + } + + /*** + * Sets the product identifier + * @param String $id + */ + public function setId($id) + { + $this->id = $id; + } + + /*** + * @return String the product description + */ + public function getDescription() + { + return $this->description; + } + + /*** + * Sets the product description + * @param String $description + */ + public function setDescription($description) + { + $this->description = PagSeguroHelper::formatString($description, 255); + } + + /*** + * @return integer the quantity + */ + public function getQuantity() + { + return $this->quantity; + } + + /*** + * Sets the quantity + * @param String $quantity + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + } + + /*** + * @return the unit amount for this item + */ + public function getAmount() + { + return $this->amount; + } + + /*** + * sets the unit amount fot this item + * @param String $amount + */ + public function setAmount($amount) + { + $this->amount = $amount; + } + + /*** + * @return float the weight + */ + public function getWeight() + { + return $this->weight; + } + + /*** + * Sets the single unit weight + * @param String $weight + */ + public function setWeight($weight) + { + $this->weight = $weight; + } + + /*** + * @return float the unit shipping cost for this item + */ + public function getShippingCost() + { + return $this->shippingCost; + } + + /*** + * Sets the unit shipping cost for this item + * @param String $shippingCost + */ + public function setShippingCost($shippingCost) + { + $this->shippingCost = $shippingCost; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroMetaData.class.php b/PagSeguroLibrary/domain/PagSeguroMetaData.class.php new file mode 100644 index 0000000..a21276a --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroMetaData.class.php @@ -0,0 +1,71 @@ + 0) { + $this->setItems($items); + } + } + + /*** + * @param PagSeguroMetaDataItem $metaDataItem + */ + public function addItem(PagSeguroMetaDataItem $metaDataItem) + { + $this->items[] = $metaDataItem; + } + + /*** + * @param array $items + */ + public function setItems(array $items) + { + $this->items = $items; + } + + /*** + * @return array + */ + public function getItems() + { + if ($this->items == null) { + $this->items = array(); + } + return $this->items; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroMetaDataItem.class.php b/PagSeguroLibrary/domain/PagSeguroMetaDataItem.class.php new file mode 100644 index 0000000..f82a489 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroMetaDataItem.class.php @@ -0,0 +1,146 @@ +setKey($key); + } + if (isset($value) && !PagSeguroHelper::isEmpty($value)) { + $this->setValue($value); + } + if (isset($group) && !PagSeguroHelper::isEmpty($group)) { + $this->setGroup($group); + } + } + + /*** + * Gets the metadata item key + * @return string + */ + public function getKey() + { + return $this->key; + } + + /*** + * Sets the metadata item key + * + * @param string $key + */ + public function setKey($key) + { + $this->key = $key; + } + + /*** + * Gets metadata item value + * @return string + */ + public function getValue() + { + return $this->value; + } + + /*** + * Sets metadata item value + * + * @param string $value + */ + public function setValue($value) + { + $this->value = $this->normalizeParameter($value); + } + + /*** + * Gets metadata item group + * + * @return int + */ + public function getGroup() + { + return $this->group; + } + + /*** + * Sets metadata item group + * + * @param int $group + */ + public function setGroup($group) + { + $this->group = (int) $group; + } + + /*** + * Normalize metadata item value + * @param string $parameterValue + * @return string + */ + private function normalizeParameter($parameterValue) + { + + $parameterValue = PagSeguroHelper::formatString($parameterValue, 100, ''); + + switch ($this->getKey()) { + case PagSeguroMetaDataItemKeys::getItemKeyByDescription('CPF do passageiro'): + $parameterValue = PagSeguroHelper::getOnlyNumbers($parameterValue); + break; + case PagSeguroMetaDataItemKeys::getItemKeyByDescription('Tempo no jogo em dias'): + $parameterValue = PagSeguroHelper::getOnlyNumbers($parameterValue); + break; + case PagSeguroMetaDataItemKeys::getItemKeyByDescription('Celular de recarga'): + break; + default: + break; + } + return $parameterValue; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroMetaDataItemKeys.class.php b/PagSeguroLibrary/domain/PagSeguroMetaDataItemKeys.class.php new file mode 100644 index 0000000..9ffb0b2 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroMetaDataItemKeys.class.php @@ -0,0 +1,88 @@ + 'Passenger CPF', + 'PASSENGER_PASSPORT' => 'Passager passport', + 'ORIGIN_CITY' => 'Origin city', + 'DESTINATION_CITY' => 'Destination city', + 'ORIGIN_AIRPORT_CODE' => 'Airport source code', + 'DESTINATION_AIRPORT_CODE' => 'Destination airport code', + 'GAME_NAME' => 'Game name', + 'PLAYER_ID' => 'Player identification', + 'TIME_IN_GAME_DAYS' => 'In days game time', + 'MOBILE_NUMBER' => 'Recharge cell', + 'PASSENGER_NAME' => 'Passenger name' + ); + + /*** + * Get available item key list for metadata use in PagSeguro transactions + * @return array + */ + public static function getAvailableItemKeysList() + { + return self::$availableItemKeysList; + } + + /*** + * Check if item key is available for PagSeguro + * @param string $itemKey + * @return boolean + */ + public static function isItemKeyAvailable($itemKey) + { + $itemKey = strtoupper($itemKey); + return (isset(self::$availableItemKeysList[$itemKey])); + } + + /*** + * Gets item description by key + * @param string $itemKey + * @return string + */ + public static function getItemDescriptionByKey($itemKey) + { + $itemKey = strtoupper($itemKey); + if (isset(self::$availableItemKeysList[$itemKey])) { + return self::$availableItemKeysList[$itemKey]; + } else { + return false; + } + } + + /*** + * Gets item key type by description + * @param string $itemDescription + * @return string + */ + public static function getItemKeyByDescription($itemDescription) + { + return array_search(strtolower($itemDescription), array_map('strtolower', self::$availableItemKeysList)); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroNotificationType.class.php b/PagSeguroLibrary/domain/PagSeguroNotificationType.class.php new file mode 100644 index 0000000..263763b --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroNotificationType.class.php @@ -0,0 +1,75 @@ + 'transaction', + 'APPLICATION_AUTHORIZATION' => 'applicationAuthorization', + 'PRE_APPROVAL' => 'preApproval' + ); + + private $value; + + public function __construct($value = null) + { + if ($value) { + $this->setValue($value); + } + } + + public function setValue($value) + { + $this->value = $value; + } + + public function setByType($type) + { + if (isset(self::$typeList[$type])) { + $this->value = self::$typeList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + public function getValue() + { + return $this->value; + } + + /*** + * @param value + * @return the PagSeguroNotificationType corresponding to the informed value + */ + public function getTypeFromValue($value = null) + { + $value = ($value == null ? $this->value : $value); + return array_search($this->value, self::$typeList); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroOnlineDebitCheckout.class.php b/PagSeguroLibrary/domain/PagSeguroOnlineDebitCheckout.class.php new file mode 100644 index 0000000..57643f9 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroOnlineDebitCheckout.class.php @@ -0,0 +1,66 @@ +setBankName($data['bankName']); + } + } + + } + + /*** + * Sets the bank name + * @param String $name + */ + public function setBankName($name) + { + $this->bankName = $name; + } + + /*** + * @return string bank name + */ + public function getBankName() + { + return $this->bankName; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroParameter.class.php b/PagSeguroLibrary/domain/PagSeguroParameter.class.php new file mode 100644 index 0000000..aa08f13 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroParameter.class.php @@ -0,0 +1,65 @@ + 0) { + $this->setItems($items); + } + } + + public function addItem(PagSeguroParameterItem $parameterItem) + { + + if (!PagSeguroHelper::isEmpty($parameterItem->getKey())) { + if (!PagSeguroHelper::isEmpty($parameterItem->getValue())) { + $this->items[] = $parameterItem; + } else { + die('requered parameterValue.'); + } + } else { + die('requered parameterKey.'); + } + } + + public function setItems(array $items) + { + $this->items = $items; + } + + public function getItems() + { + if ($this->items == null) { + $this->items = array(); + } + return $this->items; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroParameterItem.class.php b/PagSeguroLibrary/domain/PagSeguroParameterItem.class.php new file mode 100644 index 0000000..16f19b4 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroParameterItem.class.php @@ -0,0 +1,120 @@ +setKey($key); + } + if (isset($value) && !PagSeguroHelper::isEmpty($value)) { + $this->setValue($value); + } + if (isset($group) && !PagSeguroHelper::isEmpty($group)) { + $this->setGroup($group); + } + } + + /*** + * Gets the parameter item key + * @return string + */ + public function getKey() + { + return $this->key; + } + + /*** + * Sets the parameter item key + * + * @param string $key + */ + public function setKey($key) + { + $this->key = $key; + } + + /*** + * Gets parameter item value + * @return string + */ + public function getValue() + { + return $this->value; + } + + /*** + * Sets parameter item value + * + * @param string $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /*** + * Gets parameter item group + * + * @return int + */ + public function getGroup() + { + return $this->group; + } + + /*** + * Sets parameter item group + * + * @param int $group + */ + public function setGroup($group) + { + $this->group = (int) $group; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMethod.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMethod.class.php new file mode 100644 index 0000000..e34450a --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMethod.class.php @@ -0,0 +1,98 @@ +setType($type); + } + if ($code) { + $this->setCode($code); + } + } + + /*** + * @return the payment method type + */ + public function getType() + { + return $this->type; + } + + /*** + * Sets the payment method type + * @param PagSeguroPaymentMethodType $type + */ + public function setType($type) + { + if ($type instanceof PagSeguroPaymentMethodType) { + $this->type = $type; + } else { + $this->type = new PagSeguroPaymentMethodType($type); + } + } + + /*** + * @return the code + */ + public function getCode() + { + return $this->code; + } + + /*** + * Sets the payment method code + * @param PagSeguroPaymentMethodCode $code + */ + public function setCode($code) + { + if ($code instanceof PagSeguroPaymentMethodCode) { + $this->code = $code; + } else { + $this->code = new PagSeguroPaymentMethodCode($code); + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMethodCode.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMethodCode.class.php new file mode 100644 index 0000000..8e6cd6b --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMethodCode.class.php @@ -0,0 +1,202 @@ + 101, + /*** + * MasterCard + */ + 'MASTERCARD_CREDIT_CARD' => 102, + /*** + * American Express + */ + 'AMEX_CREDIT_CARD' => 103, + /*** + * Diners + */ + 'DINERS_CREDIT_CARD' => 104, + /*** + * Hipercard + */ + 'HIPERCARD_CREDIT_CARD' => 105, + /*** + * Aura + */ + 'AURA_CREDIT_CARD' => 106, + /*** + * Elo + */ + 'ELO_CREDIT_CARD' => 107, + /*** + * PLENOCard + */ + 'PLENOCARD_CREDIT_CARD' => 108, + /*** + * PersonalCard + */ + 'PERSONALCARD_CREDIT_CARD' => 109, + /*** + * JCB + */ + 'JCB_CREDIT_CARD' => 110, + /*** + * Discover + */ + 'DISCOVER_CREDIT_CARD' => 111, + /*** + * BrasilCard + */ + 'BRASILCARD_CREDIT_CARD' => 112, + /*** + * FORTBRASIL + */ + 'FORTBRASIL_CREDIT_CARD' => 113, + /*** + * CARDBAN + */ + 'CARDBAN_CREDIT_CARD' => 114, + /*** + * VALECARD + */ + 'VALECARD_CREDIT_CARD' => 115, + /*** + * Cabal + */ + 'CABAL_CREDIT_CARD' => 116, + /*** + * Mais! + */ + 'MAIS_CREDIT_CARD' => 117, + /*** + * Avista + */ + 'AVISTA_CREDIT_CARD' => 118, + /*** + * GranCard + */ + 'GRANDCARD_CREDIT_CARD' => 119, + /*** + * Bradesco - boleto - is a form of invoicing in Brazil + */ + 'BRADESCO_BOLETO' => 201, + /*** + * Santander - boleto - is a form of invoicing in Brazil + */ + 'SANTANDER_BOLETO' => 202, + /*** + * Bradesco on-line transfer + */ + 'BRADESCO_ONLINE_TRANSFER' => 301, + /*** + * Itau on-line transfer + */ + 'ITAU_ONLINE_TRANSFER' => 302, + /*** + * Unibanco on-line transfer + */ + 'UNIBANCO_ONLINE_TRANSFER' => 303, + /*** + * Banco do Brasil on-line transfer + */ + 'BANCO_BRASIL_ONLINE_TRANSFER' => 304, + /*** + * Banco Real on-line transfer + */ + 'REAL_ONLINE_TRANSFER' => 305, + /*** + * Banrisul on-line transfer + */ + 'BANRISUL_ONLINE_TRANSFER' => 306, + /*** + * HSBC on-line transfer + */ + 'HSBC_ONLINE_TRANSFER' => 307, + /*** + * PagSeguro account balance + */ + 'PS_BALANCE' => 401, + /*** + * OiPaggo + */ + 'OI_PAGGO' => 501, + /*** + * Banco do Brasil direct deposit + */ + 'BANCO_BRASIL_DIRECT_DEPOSIT' => 701 + ); + + /*** + * Payment method code + * Example: 101 + */ + private $value; + + public function __construct($value = null) + { + if ($value) { + $this->setValue($value); + } + } + + public function setValue($value) + { + $this->value = $value; + } + + public function setByType($type) + { + if (isset(self::$codeList[$type])) { + $this->value = self::$codeList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + /*** + * @return integer the payment method code value + * Example: 101 + */ + public function getValue() + { + return $this->value; + } + + /*** + * @param $value + * @return PagSeguroPaymentMethodCode the corresponding to the informed value + */ + public function getTypeFromValue($value = null) + { + $value = ($value == null ? $this->value : $value); + return array_search($value, self::$codeList); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfig.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfig.class.php new file mode 100644 index 0000000..9e56636 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfig.class.php @@ -0,0 +1,71 @@ + 0) { + $this->setConfig($config); + } + } + + /*** + * @param PagSeguroPaymentMethodConfigItem $itemConfig + */ + public function addConfig(PagSeguroPaymentMethodConfigItem $itemConfig) + { + $this->config[] = $itemConfig; + } + + /*** + * @param array $config + */ + public function setConfig(array $config) + { + $this->config = $config; + } + + /*** + * @return array + */ + public function getConfig() + { + if ($this->config == null) { + $this->config = array(); + } + return $this->config; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigItem.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigItem.class.php new file mode 100644 index 0000000..5b83ed3 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigItem.class.php @@ -0,0 +1,121 @@ +setKey($key); + } + if (isset($value) && !PagSeguroHelper::isEmpty($value)) { + $this->setValue($value); + } + if (isset($group) && !PagSeguroHelper::isEmpty($group)) { + $this->setGroup($group); + } + } + + /*** + * Gets the payment method config item key + * @return string + */ + public function getKey() + { + return $this->key; + } + + /*** + * Sets the payment method config item key + * + * @param string $key + */ + public function setKey($key) + { + $this->key = $key; + } + + /*** + * Gets payment method config item value + * @return string + */ + public function getValue() + { + return $this->value; + } + + /*** + * Sets payment method config item value + * + * @param string $value + */ + public function setValue($value) + { + $this->value = PagSeguroHelper::decimalFormat($value); + } + + /*** + * Gets payment method config item group + * + * @return int + */ + public function getGroup() + { + return $this->group; + } + + /*** + * Sets payment method config item group + * + * @param int $group + */ + public function setGroup($group) + { + $this->group = $group; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigKeys.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigKeys.class.php new file mode 100644 index 0000000..592401e --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMethodConfigKeys.class.php @@ -0,0 +1,80 @@ + 'Percentual de Desconto', + 'MAX_INSTALLMENTS_NO_INTEREST' => 'Parcelamento sem Acréscimo', + 'MAX_INSTALLMENTS_LIMIT' => 'Limite de Parcelamento' + ); + + /*** + * Get available config key list for payment method config use in PagSeguro transactions + * @return array + */ + public static function getAvailableKeysList() + { + return self::$availableKeyList; + } + + /*** + * Check if config key is available for PagSeguro + * @param string $configKey + * @return boolean + */ + public static function isKeyAvailable($configKey) + { + $configKey = strtoupper($configKey); + return (isset(self::$availableKeyList[$configKey])); + } + + /*** + * Gets config description by key + * @param string $configKey + * @return string + */ + public static function getDescriptionByKey($configKey) + { + $configKey = strtoupper($configKey); + if (isset(self::$availableKeyList[$configKey])) { + return self::$availableKeyList[$configKey]; + } else { + return false; + } + } + + /*** + * Gets config key type by description + * @param string $configDescription + * @return string + */ + public static function getKeyByDescription($configDescription) + { + return array_search(strtolower($configDescription), array_map('strtolower', self::$availableKeyList)); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMethodGroups.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMethodGroups.class.php new file mode 100644 index 0000000..464c72f --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMethodGroups.class.php @@ -0,0 +1,82 @@ + 'Payment with Credit Card', + 'BOLETO' => 'Payment with Boleto', + 'EFT' => 'Payment with Online Debit', + 'BALANCE' => 'Payment with PagSeguro Balance', + 'DEPOSIT' => 'Payment with Deposit' + ); + + /*** + * Get available payment method groups list for payment method config use in PagSeguro transactions + * @return array + */ + public static function getAvailableGroupList() + { + return self::$availableGroupList; + } + + /*** + * Check if payment method groups is available for PagSeguro + * @param string $key + * @return boolean + */ + public static function isKeyAvailable($key) + { + $key = strtoupper($key); + return (isset(self::$availableGroupList[$key])); + } + + /*** + * Gets group description by key + * @param string $key + * @return string + */ + public static function getDescriptionByKey($key) + { + $key = strtoupper($key); + if (isset(self::$availableGroupList[$key])) { + return self::$availableGroupList[$key]; + } else { + return false; + } + } + + /*** + * Gets group type by description + * @param string $description + * @return string + */ + public static function getGroupByDescription($description) + { + return array_search(strtolower($description), array_map('strtolower', self::$availableGroupList)); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMethodType.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMethodType.class.php new file mode 100644 index 0000000..f33d11d --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMethodType.class.php @@ -0,0 +1,91 @@ + 1, + /*** Boleto - is a form of invoicing in Brazil */ + 'BOLETO' => 2, + /*** Online transfer */ + 'ONLINE_TRANSFER' => 3, + /*** PagSeguro account balance */ + 'BALANCE' => 4, + /*** OiPaggo */ + 'OI_PAGGO' => 5, + /*** Direct deposit */ + 'DIRECT_DEPOSIT' => 7 + ); + + /*** + * Payment method type value + * Example: 1 + * @var integer + */ + private $value; + + public function __construct($value = null) + { + if ($value) { + $this->setValue($value); + } + } + + public function setValue($value) + { + $this->value = $value; + } + + public function setByType($type) + { + if (isset(self::$typeList[$type])) { + $this->value = self::$typeList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + /*** + * @return integer payment method type value + * Example: 1 + */ + public function getValue() + { + return $this->value; + } + + /*** + * @param value + * @return PagSeguroPaymentMethodType the corresponding to the informed value + */ + public function getTypeFromValue($value = null) + { + $value = ($value == null ? $this->value : $value); + return array_search($value, self::$typeList); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentMode.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentMode.class.php new file mode 100644 index 0000000..7ecddf1 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentMode.class.php @@ -0,0 +1,86 @@ + 'default', + 'GATEWAY' => 'gateway' + ); + + /*** + * Payment mode value + * Example: DEFAULT + * @var string + */ + private $value; + + /*** + * Initializes a new instance of the PagSeguroPaymentMode class + * @param array|object $value + */ + public function __construct($value) + { + + if (array_key_exists($value, $this->modeList)) { + $this->setValue($this->modeList[$value]); + } else { + throw new Exception("Payment mode not found"); + } + } + + /*** + * Set the payment mode value + * @param string value + */ + private function setValue($value) + { + $this->value = $value; + } + + /*** + * @return string $value of payment mode value + */ + public function getValue() + { + return $this->value; + } + + /*** + * Find a PagSeguroPaymentMode in a list + * @param value + * @return PagSeguroPaymentMode the corresponding to the informed value + */ + public static function fromValue($value) + { + try { + return array_search(strtoupper($value), $this->modeList); + } catch (Exception $e) { + return null; + } + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPaymentRequest.class.php b/PagSeguroLibrary/domain/PagSeguroPaymentRequest.class.php new file mode 100644 index 0000000..9c4a772 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPaymentRequest.class.php @@ -0,0 +1,97 @@ +preApproval = $preApproval; + } + /** + * @return mixed + */ + public function getPreApproval() + { + return $this->preApproval; + } + + /*** + * Calls the PagSeguro web service and register this request for payment + * + * @param PagSeguroCredentials $credentials, lighbox + * @return String The URL to where the user needs to be redirected to in order to complete the payment process or + * the CODE when use lightbox + */ + public function register(PagSeguroCredentials $credentials, $onlyCheckoutCode = false) + { + return PagSeguroPaymentService::checkoutRequest($credentials, $this, $onlyCheckoutCode); + } + + /*** + * Verify if the adress of NotificationURL or RedirectURL is for tests and return empty + * @param type $url + * @return type + */ + public function verifyURLTest($url) + { + $adress = array( + '127.0.0.1', + '::1' + ); + + $urlReturn = null; + foreach ($adress as $item) { + $find = strpos($url, $item); + + if ($find) { + $urlReturn = ''; + break; + } else { + $urlReturn = $url; + } + } + + return $urlReturn; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPhone.class.php b/PagSeguroLibrary/domain/PagSeguroPhone.class.php new file mode 100644 index 0000000..0c206f9 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPhone.class.php @@ -0,0 +1,114 @@ +areaCode = ($areaCode == null ? null : $areaCode); + $this->number = ($number == null ? null : $number); + return $this; + } + + /*** + * @return int the area code + */ + public function getAreaCode() + { + return $this->areaCode; + } + + /*** + * @return int the number + */ + public function getNumber() + { + return $this->number; + } + + /*** + * Sets the area code + * @param String $areaCode + * @return PagSeguroPhone + */ + public function setAreaCode($areaCode) + { + $this->areaCode = $areaCode; + return $this; + } + + /*** + * Sets the number + * @param String $number + * @return PagSeguroPhone + */ + public function setNumber($number) + { + $this->number = $number; + return $this; + } + + /*** + * Sets the number from a formatted string + * + * @param $number String formatted string like (099) [9]9999-9999 + * @return $this + */ + public function setFullPhone($number) + { + /** We clean the string that is coming. Can be formatted or not */ + + $number = preg_replace("/[^0-9]/", '', $number); + $number = $number[0] == 0 ? substr($number, 1) : $number; + + $number = str_split($number, 1); + $areaCode = array_shift($number) . array_shift($number); + $phone = implode('', $number); + + $this->setAreaCode($areaCode); + $this->setNumber($phone); + + return $this->areaCode . $this->number; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPreApproval.class.php b/PagSeguroLibrary/domain/PagSeguroPreApproval.class.php new file mode 100644 index 0000000..bdd016c --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPreApproval.class.php @@ -0,0 +1,287 @@ + + * @copyright 2007-2014 PagSeguro Internet Ltda. + * @license http://www.apache.org/licenses/LICENSE-2.0 + */ + +/*** + * Class PagSeguroPreApproval + * Represents a PagSeguro preApproval transaction + * + * @property PagSeguroSender $sender + * + */ +class PagSeguroPreApproval +{ + /*** + * Transaction name + */ + private $name; + + /*** + * Transaction date + */ + private $date; + + /*** + * Last event date + * Date the last notification about this transaction was sent + */ + private $lastEventDate; + + /*** + * Transaction code + */ + private $code; + + /*** + * Reference code + * You can use the reference code to store an identifier so you can + * associate the PagSeguro transaction to a transaction in your system. + */ + private $reference; + + /*** + * Recovery code + */ + private $tracker; + + /*** + * Transaction Status + * @see PagSeguroTransactionStatus + * @var PagSeguroTransactionStatus + */ + private $status; + + /*** + * Pre Approval Charge + */ + private $charge; + + /*** + * Payer information, who is sending money + * @see PagSeguroSender + * @var PagSeguroSender + */ + private $sender; + + public function __construct($data = null) + { + if (is_array($data)) { + $this->setName($data['name']); + $this->setDate($data['date']); + $this->setLastEventDate($data['lastEventDate']); + $this->setCode($data['code']); + $this->setReference($data['reference']); + $this->setTracker($data['tracker']); + $this->setStatus(new PagSeguroPreApprovalStatus($data['status'])); + $this->setCharge($data['charge']); + } + } + + /*** + * @return String the transaction name + */ + public function getName() + { + return $this->name; + } + + /*** + * Sets the transaction name + * + * @param string name + */ + public function setName($name) + { + $this->name = $name; + } + + /*** + * Date the last notification about this transaction was sent + * @return datetime the last event date + */ + public function getLastEventDate() + { + return $this->lastEventDate; + } + + /*** + * Sets the last event date + * + * @param lastEventDate + */ + public function setLastEventDate($lastEventDate) + { + $this->lastEventDate = $lastEventDate; + } + + /*** + * @return datetime the transaction date + */ + public function getDate() + { + return $this->date; + } + + /*** + * Sets the transaction date + * + * @param string date + */ + public function setDate($date) + { + $this->date = $date; + } + + /*** + * @return string the transaction code + */ + public function getCode() + { + return $this->code; + } + + /*** + * Sets the transaction code + * + * @param code + */ + public function setCode($code) + { + $this->code = $code; + } + + /*** + * You can use the reference code to store an identifier so you can + * associate the PagSeguro transaction to a transaction in your system. + * + * @return string the reference code + */ + public function getReference() + { + return $this->reference; + } + + /*** + * Sets the reference code + * + * @param reference + */ + public function setReference($reference) + { + $this->reference = $reference; + } + + /*** + * @return string the tracker code + */ + public function getTracker() + { + return $this->tracker; + } + + /*** + * Sets the tracker code + * + * @param code + */ + public function setTracker($tracker) + { + $this->tracker = $tracker; + } + + /*** + * @return string the charge + */ + public function getCharge() + { + return $this->charge; + } + + /*** + * Sets the charge + * + * @param code + */ + public function setCharge($charge) + { + $this->charge = $charge; + } + + /*** + * @return PagSeguroPreApprovalStatus the transaction status + * @see PagSeguroPreApprovalStatus + */ + public function getStatus() + { + return $this->status; + } + + /*** + * Sets the preApproval status + * @param PagSeguroPreApprovalStatus $status + */ + public function setStatus(PagSeguroPreApprovalStatus $status) + { + $this->status = $status; + } + + + + /*** + * @return PagSeguroSender the sender information, who is sending money in this transaction + * @see PagSeguroSender + */ + public function getSender() + { + return $this->sender; + } + + /*** + * Sets the sender information, who is sending money in this transaction + * @param PagSeguroSender $sender + */ + public function setSender(PagSeguroSender $sender) + { + $this->sender = $sender; + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + + $preApproval = array(); + $preApproval['code'] = $this->code; + $preApproval['email'] = $this->sender ? $this->sender->getEmail() : "null"; + $preApproval['date'] = $this->date; + $preApproval['reference'] = $this->reference; + $preApproval['status'] = $this->status ? $this->status->getValue() : "null"; + $preApproval['charge'] = $this->charge; + $preApproval['tracker'] = $this->tracker; + + $preApproval = "PreApproval: " . var_export($preApproval, true); + + return $preApproval; + + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPreApprovalCharge.class.php b/PagSeguroLibrary/domain/PagSeguroPreApprovalCharge.class.php new file mode 100644 index 0000000..87536de --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPreApprovalCharge.class.php @@ -0,0 +1,159 @@ + + * @copyright 2007-2014 PagSeguro Internet Ltda. + * @license http://www.apache.org/licenses/LICENSE-2.0 + */ + +/*** + * Represents a preApproval request + */ +class PagSeguroPreApprovalCharge +{ + + /*** + * Products/items in this pre approval charge + */ + private $items; + /** + * @var + */ + private $reference; + /** + * @var + */ + private $preApprovalCode; + + /*** + * @return array the items/products list in this payment request + */ + public function getItems() + { + return $this->items; + } + + /*** + * Sets the items/products list in this payment request + * @param array $items + */ + public function setItems(array $items) + { + if (is_array($items)) { + $i = array(); + foreach ($items as $key => $item) { + if ($item instanceof PagSeguroItem) { + $i[$key] = $item; + } else { + if (is_array($item)) { + $i[$key] = new PagSeguroItem($item); + } + } + } + $this->items = $i; + } + } + + /*** + * Adds a new product/item in this payment request + * + * @param String $id + * @param String $description + * @param String $quantity + * @param String $amount + */ + public function addItem( + $id, + $description = null, + $quantity = null, + $amount = null + ) { + $param = $id; + if ($this->items == null) { + $this->items = array(); + } + if (is_array($param)) { + array_push($this->items, new PagSeguroItem($param)); + } else { + if ($param instanceof PagSeguroItem) { + array_push($this->items, $param); + } else { + $item = new PagSeguroItem(); + $item->setId($param); + $item->setDescription($description); + $item->setQuantity($quantity); + $item->setAmount($amount); + array_push($this->items, $item); + } + } + } + + /** + * @return mixed + */ + public function getReference() + { + return $this->reference; + } + + /** + * @param mixed $reference + */ + public function setReference($reference) + { + $this->reference = $reference; + } + + /** + * @return mixed + */ + public function getPreApprovalCode() + { + return $this->preApprovalCode; + } + + /** + * @param mixed $preApprovalCode + */ + public function setPreApprovalCode($preApprovalCode) + { + $this->preApprovalCode = $preApprovalCode; + } + + /** + * @param PagSeguroCredentials $credentials + * @return array|null|PagSeguroParserData + */ + public function register(PagSeguroCredentials $credentials) + { + return PagSeguroPreApprovalService::paymentCharge($credentials, $this); + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + + $request = array(); + $request['Reference'] = $this->reference; + $request['PagSeguroPreApprovalCode'] = $this->preApprovalCode; + + return "PagSeguroPaymentCharge: " . var_export($request, true); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPreApprovalRequest.class.php b/PagSeguroLibrary/domain/PagSeguroPreApprovalRequest.class.php new file mode 100644 index 0000000..54891e4 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPreApprovalRequest.class.php @@ -0,0 +1,364 @@ + + * @copyright 2007-2014 PagSeguro Internet Ltda. + * @license http://www.apache.org/licenses/LICENSE-2.0 + */ + +/*** + * Represents a preApproval request + */ +class PagSeguroPreApprovalRequest extends PagSeguroRequest +{ + + /** + * @var + */ + private $reviewURL; + /** + * @var + */ + private $receiverEmail; + /** + * @var + */ + private $preApprovalMaxTotalAmount; + /** + * @var + */ + private $preApprovalMaxAmountPerPeriod; + /** + * @var + */ + private $preApprovalFinalDate; + /** + * @var + */ + private $preApprovalInitialDate; + /** + * @var + */ + private $preApprovalDayOfMonth; + /** + * @var + */ + private $preApprovalDayOfWeek; + /** + * @var + */ + private $preApprovalDayOfYear; + /** + * @var + */ + private $preApprovalPeriod; + /** + * @var + */ + private $preApprovalAmountPerPayment; + /** + * @var + */ + private $preApprovalMaxAmountPerPayment; + /** + * @var + */ + private $preApprovalMaxPaymentsPerPeriod; + /** + * @var + */ + private $preApprovalDetails; + /** + * @var + */ + private $preApprovalName; + /** + * @var + */ + private $preApprovalCharge; + + /*** + * Sets the review URL + * + * Uri to where the PagSeguro payment page should redirect the user if they want to change the Pre Approval rules + * + * @param String $reviewURL + */ + public function setReviewURL($reviewURL) + { + $this->reviewURL = $this->verifyURLTest($reviewURL); + } + /** + * @return mixed the Review Url + */ + public function getReviewURL() + { + return $this->reviewURL; + } + + /** + * Sets the preApprovalReceiverEmail for this pre approval + * @param string $receiverEmail + */ + public function setReceiverEmail($receiverEmail) + { + $this->receiverEmail = $receiverEmail; + } + /** + * @return string + */ + public function getReceiverEmail() + { + return $this->receiverEmail; + } + + /*** + * Sets the preApprovalMaxTotalAmount for this pre approval + * @param double $value + */ + public function setPreApprovalMaxTotalAmount($value) + { + $this->preApprovalMaxTotalAmount = $value; + } + /*** + * @return double the reference of preApprovalMaxTotalAmount + */ + public function getPreApprovalMaxTotalAmount() + { + return $this->preApprovalMaxTotalAmount; + } + + /*** + * Sets the preApprovalMaxAmountPerPeriod for this pre approval + * @param double $value + */ + public function setPreApprovalMaxAmountPerPeriod($value) + { + $this->preApprovalMaxAmountPerPeriod = $value; + } + /*** + * @return double the reference of preApprovalMaxAmountPerPeriod + */ + public function getPreApprovalMaxAmountPerPeriod() + { + return $this->preApprovalMaxAmountPerPeriod; + } + + /*** + * Sets the preApprovalFinalDate for this pre approval + * @param ISODate $date + */ + public function setPreApprovalFinalDate($date) + { + $this->preApprovalFinalDate = $date; + } + /*** + * @return date the reference of preApprovalFinalDate + */ + public function getPreApprovalFinalDate() + { + return $this->preApprovalFinalDate; + } + + /*** + * Sets the preApprovalInitialDate for this pre approval + * @param ISODate $date + */ + public function setPreApprovalInitialDate($date) + { + $this->preApprovalInitialDate = $date; + } + /*** + * @return date the reference of preApprovalInitialDate + */ + public function getPreApprovalInitialDate() + { + return $this->preApprovalInitialDate; + } + + /*** + * Sets the preApprovalDayOfMonth for this pre approval + * @param Number $day + */ + public function setPreApprovalDayOfMonth($day) + { + $this->preApprovalDayOfMonth = $day; + } + /*** + * @return int the reference of preApprovalInitialDate + */ + public function getPreApprovalDayOfMonth() + { + return $this->preApprovalDayOfMonth; + } + + /*** + * Sets the preApprovalDayOfWeek for this pre approval + * @param String $day + */ + public function setPreApprovalDayOfWeek($day) + { + $this->preApprovalDayOfWeek = $day; + } + /*** + * @return String the reference of preApprovalDayOfWeek + */ + public function getPreApprovalDayOfWeek() + { + return $this->preApprovalDayOfWeek; + } + + /** + * Sets the preApprovalDayOfYear for this pre approval + * @param mixed $preApprovalDayOfYear + */ + public function setPreApprovalDayOfYear($preApprovalDayOfYear) + { + $this->preApprovalDayOfYear = $preApprovalDayOfYear; + } + /** + * @return mixed + */ + public function getPreApprovalDayOfYear() + { + return $this->preApprovalDayOfYear; + } + + /*** + * Sets the preApprovalPeriod for this pre approval + * @param String $period + */ + public function setPreApprovalPeriod($period) + { + $this->preApprovalPeriod = $period; + } + /*** + * @return String the reference of preApprovalPeriod + */ + public function getPreApprovalPeriod() + { + return $this->preApprovalPeriod; + } + + /*** + * Sets the preApprovalAmountPerPayment value for the recurrent payment + * @param double $value + */ + public function setPreApprovalAmountPerPayment($value) + { + $this->preApprovalAmountPerPayment = $value; + } + /*** + * @return double the reference of preApprovalAmountPerPayment + */ + public function getPreApprovalAmountPerPayment() + { + return $this->preApprovalAmountPerPayment; + } + + /** + * Sets the preApprovalMaxAmountPerPayment value for the recurrent payment + * @param double $preApprovalMaxAmountPerPayment + */ + public function setPreApprovalMaxAmountPerPayment($preApprovalMaxAmountPerPayment) + { + $this->preApprovalMaxAmountPerPayment = $preApprovalMaxAmountPerPayment; + } + /** + * @return double + */ + public function getPreApprovalMaxAmountPerPayment() + { + return $this->preApprovalMaxAmountPerPayment; + } + + /** + * Sets the preApprovalMaxPaymentsPerPeriod value for the recurrent period + * @param double $preApprovalMaxPaymentsPerPeriod + */ + public function setPreApprovalMaxPaymentsPerPeriod($preApprovalMaxPaymentsPerPeriod) + { + $this->preApprovalMaxPaymentsPerPeriod = $preApprovalMaxPaymentsPerPeriod; + } + /** + * @return double + */ + public function getPreApprovalMaxPaymentsPerPeriod() + { + return $this->preApprovalMaxPaymentsPerPeriod; + } + + /*** + * Sets the preApprovalDetails for the transaction + * @param String $details + */ + public function setPreApprovalDetails($details) + { + $this->preApprovalDetails = $details; + } + /*** + * @return String the reference of preApprovalDetails + */ + public function getPreApprovalDetails() + { + return $this->preApprovalDetails; + } + + /*** + * Sets the preApprovalName (title) for the transaction + * @param String $name + */ + public function setPreApprovalName($name) + { + $this->preApprovalName = $name; + } + /*** + * @return String the reference of preApprovalName (title) + */ + public function getPreApprovalName() + { + return $this->preApprovalName; + } + + /*** + * Sets the preApprovalCharge type (auto, manual) + * @param String $type + */ + public function setPreApprovalCharge($type) + { + $this->preApprovalCharge = $type; + } + + /*** + * @return String the reference of pre approval charge + */ + public function getPreApprovalCharge() + { + return $this->preApprovalCharge; + } + + /*** + * Register the preApproval + * @param PagSeguroCredentials $credentials + * @param bool $onlyCheckoutCode + */ + public function register(PagSeguroCredentials $credentials, $onlyCheckoutCode = false) + { + return PagSeguroPreApprovalService::createPreApprovalRequest($credentials, $this); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPreApprovalSearchResult.class.php b/PagSeguroLibrary/domain/PagSeguroPreApprovalSearchResult.class.php new file mode 100644 index 0000000..01faf0d --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPreApprovalSearchResult.class.php @@ -0,0 +1,50 @@ +preApprovals; + } + + /** + * @param array $preApprovals + */ + public function setPreApprovals(array $preApprovals) + { + $this->preApprovals = $preApprovals; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroPreApprovalStatus.class.php b/PagSeguroLibrary/domain/PagSeguroPreApprovalStatus.class.php new file mode 100644 index 0000000..527f392 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroPreApprovalStatus.class.php @@ -0,0 +1,111 @@ + + * @copyright 2007-2014 PagSeguro Internet Ltda. + * @license http://www.apache.org/licenses/LICENSE-2.0 + */ + +/*** + * Defines a list of known transaction statuses. + * This class is not an enum to enable the introduction of new transaction status. + * without breaking this version of the library. + */ +class PagSeguroPreApprovalStatus +{ + + /*** + * @var array + */ + private static $statusList = array( + 'INITIATED' => 0, + 'PENDING' => 1, + 'ACTIVE' => 2, + 'CANCELLED' => 3, + 'CANCELLED_BY_RECEIVER' => 4, + 'CANCELLED_BY_SENDER' => 5, + 'EXPIRED' => 6 + ); + + /*** + * the value of the transaction status + * Example: 3 + */ + private $value; + + /*** + * @param null $value + */ + public function __construct($value = null) + { + if ($value) { + if (!isset(self::$statusList[$value])) { + self::$statusList = array_merge(self::$statusList, array($value => count(self::$statusList))); + } + $this->value = self::$statusList[$value]; + } + } + + /*** + * @param $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /*** + * @param $type + * @throws Exception + */ + public function setByType($type) + { + if (isset(self::$statusList[$type])) { + $this->value = self::$statusList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + /*** + * @return integer the status value. + */ + public function getValue() + { + return $this->value; + } + + /*** + * @param value + * @return String the transaction status corresponding to the informed status value + */ + public function getTypeFromValue($value = null) + { + $value = ($value == null ? $this->value : $value); + return array_search($this->value, self::$statusList); + } + + /*** + * Get status list + * @return array + */ + public static function getStatusList() + { + return self::$statusList; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroRequest.class.php b/PagSeguroLibrary/domain/PagSeguroRequest.class.php new file mode 100644 index 0000000..14ebdc6 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroRequest.class.php @@ -0,0 +1,754 @@ +currency; + } + + /*** + * Sets the currency + * @param String $currency + */ + public function setCurrency($currency) + { + $this->currency = $currency; + } + + /*** + * @return PagSeguroShipping the shipping information for this payment request + * @see PagSeguroShipping + */ + public function getShipping() + { + return $this->shipping; + } + + /*** + * Sets the shipping information for this payment request + * @param PagSeguroShipping $address + * @param PagSeguroShippingType $type + */ + public function setShipping($address, $type = null) + { + $param = $address; + if ($param instanceof PagSeguroShipping) { + $this->shipping = $param; + } else { + $shipping = new PagSeguroShipping(); + if (is_array($param)) { + $shipping->setAddress(new PagSeguroAddress($param)); + } else { + if ($param instanceof PagSeguroAddress) { + $shipping->setAddress($param); + } + } + if ($type) { + if ($type instanceof PagSeguroShippingType) { + $shipping->setType($type); + } else { + $shipping->setType(new PagSeguroShippingType($type)); + } + } + $this->shipping = $shipping; + } + } + + /*** + * Sets the shipping address for this payment request + * @param String $postalCode + * @param String $street + * @param String $number + * @param String $complement + * @param String $district + * @param String $city + * @param String $state + * @param String $country + */ + public function setShippingAddress( + $postalCode = null, + $street = null, + $number = null, + $complement = null, + $district = null, + $city = null, + $state = null, + $country = null + ) { + $param = $postalCode; + if ($this->shipping == null) { + $this->shipping = new PagSeguroShipping(); + } + if (is_array($param)) { + $this->shipping->setAddress(new PagSeguroAddress($param)); + } elseif ($param instanceof PagSeguroAddress) { + $this->shipping->setAddress($param); + } else { + $address = new PagSeguroAddress(); + $address->setPostalCode($postalCode); + $address->setStreet($street); + $address->setNumber($number); + $address->setComplement($complement); + $address->setDistrict($district); + $address->setCity($city); + $address->setState($state); + $address->setCountry($country); + $this->shipping->setAddress($address); + } + } + + /*** + * Sets the shipping type for this payment request + * @param PagSeguroShippingType $type + */ + public function setShippingType($type) + { + $param = $type; + if ($this->shipping == null) { + $this->shipping = new PagSeguroShipping(); + } + if ($param instanceof PagSeguroShippingType) { + $this->shipping->setType($param); + } else { + $this->shipping->setType(new PagSeguroShippingType($param)); + } + } + + /*** + * Sets the shipping cost for this payment request + * @param float $shippingCost + */ + public function setShippingCost($shippingCost) + { + $param = $shippingCost; + if ($this->shipping == null) { + $this->shipping = new PagSeguroShipping(); + } + + $this->shipping->setCost($param); + } + + /*** + * This value can be used to add an extra charge to the transaction + * or provide a discount in the case ExtraAmount is a negative value. + * + * @return float the extra amount + */ + public function getExtraAmount() + { + return $this->extraAmount; + } + + /*** + * @return integer the max age of this payment request + * + * After this payment request is submitted, the payment code returned + * will remain valid for the period specified. + */ + public function getMaxAge() + { + return $this->maxAge; + } + + /*** + * Sets the max age of this payment request + * After this payment request is submitted, the payment code returned + * will remain valid for the period specified here. + * + * @param maxAge + */ + public function setMaxAge($maxAge) + { + $this->maxAge = $maxAge; + } + + /*** + * Sets the extra amount + * This value can be used to add an extra charge to the transaction + * or provide a discount in the case extraAmount is a negative value. + * + * @param extraAmount + */ + public function setExtraAmount($extraAmount) + { + $this->extraAmount = $extraAmount; + } + + /** + * @return mixed + */ + public function getMaxUses() + { + return $this->maxUses; + } + + /** + * @param mixed $maxUses + */ + public function setMaxUses($maxUses) + { + $this->maxUses = $maxUses; + } + + /*** + * Sets metadata for PagSeguro checkout requests + * + * @param PagSeguroMetaData $metaData + */ + public function setMetaData($metaData) + { + $this->metadata = $metaData; + } + + /*** + * Gets metadata for PagSeguro checkout requests + * + * @return PagSeguroMetaData $metaData + */ + public function getMetaData() + { + + if ($this->metadata == null) { + $this->metadata = new PagSeguroMetaData(); + } + return $this->metadata; + } + + /*** + * add a parameter for PagSeguro metadata checkout request + * + * @param PagSeguroMetaDataItem $itemKey key + * @param PagSeguroMetaDataItem $itemValue value + * @param PagSeguroMetaDataItem $itemGroup group + */ + public function addMetaData($itemKey, $itemValue, $itemGroup = null) + { + $this->getMetaData()->addItem( + new PagSeguroMetaDataItem($itemKey, $itemValue, $itemGroup) + ); + } + + /*** + * Sets payment method config for PagSeguro checkout requests + * @param PagSeguroPaymentMethodConfig $paymentMethodConfig + */ + public function setPaymentMethodConfig($paymentMethodConfig) + { + $this->paymentMethodConfig = $paymentMethodConfig; + } + + /*** + * Gets payment method config for PagSeguro checkout requests + * @return PagSeguroPaymentMethodConfig $paymentMethodConfig + */ + public function getPaymentMethodConfig() + { + + if ($this->paymentMethodConfig == null) { + $this->paymentMethodConfig = new PagSeguroPaymentMethodConfig(); + } + return $this->paymentMethodConfig; + } + + /*** + * add a parameter for PagSeguro payment method config checkout request + * @param PagSeguroPaymentMethodConfig $itemKey key + * @param PagSeguroPaymentMethodConfig $itemValue value + * @param PagSeguroPaymentMethodGroups $itemGroup group + */ + public function addPaymentMethodConfig($itemGroup, $itemValue, $itemKey) + { + $this->getPaymentMethodConfig()->addConfig( + new PagSeguroPaymentMethodConfigItem($itemGroup, $itemValue, $itemKey) + ); + } + + /*** + * Sets acceptable groups and payment methods. + * @param PagSeguroAcceptedPaymentMethods $acceptedPaymentMethod + */ + public function setAcceptedPaymentMethod($acceptedPaymentMethod) + { + $this->acceptedPaymentMethods = $acceptedPaymentMethod; + } + + /*** + * Gets acceptable groups and payment methods + * @return PagSeguroAcceptedPaymentMethods $this->acceptedPaymentMethods + */ + public function getAcceptedPaymentMethod() + { + + if ($this->acceptedPaymentMethods == null) { + $this->acceptedPaymentMethods = new PagSeguroAcceptedPaymentMethods(); + } + return $this->acceptedPaymentMethods; + } + + /*** + * Include groups and payment methods. + */ + public function acceptPaymentMethodGroup($group, $name) + { + $this->getAcceptedPaymentMethod()->addConfig( + new PagSeguroAcceptPaymentMethod($group, $name) + ); + } + + /*** + * Exclude groups and payment methods. + */ + public function excludePaymentMethodGroup($group, $name = null) + { + $this->getAcceptedPaymentMethod()->addConfig( + new PagSeguroExcludePaymentMethod($group, $name) + ); + } + + /*** + * @return PagSeguroSender the sender + * + * Party that will be sending the Uri to where the PagSeguro payment page should redirect the + * user after the payment information is processed. + */ + public function getSender() + { + return $this->sender; + } + + /*** + * Sets the Sender, party that will be sending the money + * @param String $name + * @param String $email + * @param String $areaCode + * @param String $number + * @param String $documentType + * @param String $documentValue + */ + public function setSender( + $name, + $email = null, + $areaCode = null, + $number = null, + $documentType = null, + $documentValue = null + ) { + $param = $name; + if (is_array($param)) { + $this->sender = new PagSeguroSender($param); + } elseif ($param instanceof PagSeguroSender) { + $this->sender = $param; + } else { + $sender = new PagSeguroSender(); + $sender->setName($param); + $sender->setEmail($email); + $sender->setPhone(new PagSeguroPhone($areaCode, $number)); + $sender->addDocument($documentType, $documentValue); + $this->sender = $sender; + } + } + + /*** + * Sets the name of the sender, party that will be sending the money + * @param String $senderName + */ + public function setSenderName($senderName) + { + if ($this->sender == null) { + $this->sender = new PagSeguroSender(); + } + $this->sender->setName($senderName); + } + + /*** + * Sets the name of the sender, party that will be sending the money + * @param String $senderEmail + */ + public function setSenderEmail($senderEmail) + { + if ($this->sender == null) { + $this->sender = new PagSeguroSender(); + } + $this->sender->setEmail($senderEmail); + } + + /*** + * Sets the Sender phone number, phone of the party that will be sending the money + * + * @param areaCode + * @param number + */ + public function setSenderPhone($areaCode, $number = null) + { + $param = $areaCode; + if ($this->sender == null) { + $this->sender = new PagSeguroSender(); + } + if ($param instanceof PagSeguroPhone) { + $this->sender->setPhone($param); + } else { + $this->sender->setPhone(new PagSeguroPhone($param, $number)); + } + } + + /*** + * @return array the items/products list in this payment request + */ + public function getItems() + { + return $this->items; + } + + /*** + * Sets the items/products list in this payment request + * @param array $items + */ + public function setItems(array $items) + { + if (is_array($items)) { + $i = array(); + foreach ($items as $key => $item) { + if ($item instanceof PagSeguroItem) { + $i[$key] = $item; + } else { + if (is_array($item)) { + $i[$key] = new PagSeguroItem($item); + } + } + } + $this->items = $i; + } + } + + /*** + * Adds a new product/item in this payment request + * + * @param String $id + * @param String $description + * @param String $quantity + * @param String $amount + * @param String $weight + * @param String $shippingCost + */ + public function addItem( + $id, + $description = null, + $quantity = null, + $amount = null, + $weight = null, + $shippingCost = null + ) { + $param = $id; + if ($this->items == null) { + $this->items = array(); + } + if (is_array($param)) { + array_push($this->items, new PagSeguroItem($param)); + } else { + if ($param instanceof PagSeguroItem) { + array_push($this->items, $param); + } else { + $item = new PagSeguroItem(); + $item->setId($param); + $item->setDescription($description); + $item->setQuantity($quantity); + $item->setAmount($amount); + $item->setWeight($weight); + $item->setShippingCost($shippingCost); + array_push($this->items, $item); + } + } + } + + /** + * @param $type + * @param $value + */ + public function addSenderDocument($type, $value) + { + if ($this->getSender() instanceof PagSeguroSender) { + $this->getSender()->addDocument($type, $value); + } + } + + /*** + * URI to where the PagSeguro payment page should redirect the user after the payment information is processed. + * Typically this is a confirmation page on your web site. + * + * @return String the redirectURL + */ + public function getRedirectURL() + { + return $this->redirectURL; + } + + /*** + * Sets the redirect URL + * + * Uri to where the PagSeguro payment page should redirect the user after the payment information is processed. + * Typically this is a confirmation page on your web site. + * + * @param String $redirectURL + */ + public function setRedirectURL($redirectURL) + { + $this->redirectURL = $this->verifyURLTest($redirectURL); + } + + /*** + * @return mixed the reference of this payment request + */ + public function getReference() + { + return $this->reference; + } + + /*** + * Sets the reference of this payment request + * @param reference + */ + public function setReference($reference) + { + $this->reference = $reference; + } + + /*** + * Get the notification status url + * + * @return String + */ + public function getNotificationURL() + { + return $this->notificationURL; + } + + /*** + * Sets the url that PagSeguro will send the new notifications statuses + * + * @param String $notificationURL + */ + public function setNotificationURL($notificationURL) + { + $this->notificationURL = $this->verifyURLTest($notificationURL); + } + + /*** + * Sets parameter for PagSeguro checkout requests + * + * @param PagSeguroParameter $parameter + */ + public function setParameter($parameter) + { + $this->parameter = $parameter; + } + + /*** + * Gets parameter for PagSeguro checkout requests + * + * @return PagSeguroParameter + */ + public function getParameter() + { + if ($this->parameter == null) { + $this->parameter = new PagSeguroParameter(); + } + return $this->parameter; + } + + /*** + * add a parameter for PagSeguro checkout request + * + * @param PagSeguroParameterItem $parameterName key + * @param PagSeguroParameterItem $parameterValue value + */ + public function addParameter($parameterName, $parameterValue) + { + $this->getParameter()->addItem(new PagSeguroParameterItem($parameterName, $parameterValue)); + } + + /*** + * add a parameter for PagSeguro checkout request + * + * @param PagSeguroParameterItem $parameterName key + * @param PagSeguroParameterItem $parameterValue value + * @param PagSeguroParameterItem $parameterIndex group + */ + public function addIndexedParameter($parameterName, $parameterValue, $parameterIndex) + { + $this->getParameter()->addItem(new PagSeguroParameterItem($parameterName, $parameterValue, $parameterIndex)); + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + $email = $this->sender ? $this->sender->getEmail() : "null"; + + $request = array(); + $request['Reference'] = $this->reference; + $request['SenderEmail'] = $email; + + return "PagSeguroRequest: " . var_export($request, true); + } + + /*** + * Verify if the adress of NotificationURL or RedirectURL is for tests and return empty + * @param type $url + * @return type + */ + public function verifyURLTest($url) + { + $adress = array( + '127.0.0.1', + '::1' + ); + + $urlReturn = null; + foreach ($adress as $item) { + $find = strpos($url, $item); + + if ($find) { + $urlReturn = ''; + break; + } else { + $urlReturn = $url; + } + } + + return $urlReturn; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroSearchResult.class.php b/PagSeguroLibrary/domain/PagSeguroSearchResult.class.php new file mode 100644 index 0000000..f31de95 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroSearchResult.class.php @@ -0,0 +1,135 @@ +currentPage; + } + + /*** + * Sets the current page number + * @param integer $currentPage + */ + public function setCurrentPage($currentPage) + { + $this->currentPage = $currentPage; + } + + /*** + * @return the date/time when this search was executed + */ + public function getDate() + { + return $this->date; + } + + /*** + * Set the date/time when this search was executed + * @param date + */ + public function setDate($date) + { + $this->date = $date; + } + + /*** + * @return the number of summaries in the current page + */ + public function getResultsInThisPage() + { + return $this->resultsInThisPage; + } + + /*** + * Sets the number of summaries in the current page + * + * @param resultsInThisPage + */ + public function setResultsInThisPage($resultsInThisPage) + { + $this->resultsInThisPage = $resultsInThisPage; + } + + /*** + * @return the total number of pages + */ + public function getTotalPages() + { + return $this->totalPages; + } + + /*** + * Sets the total number of pages + * + * @param totalPages + */ + public function setTotalPages($totalPages) + { + $this->totalPages = $totalPages; + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + $result = array(); + + $result['Date'] = $this->date; + $result['CurrentPage'] = $this->currentPage; + $result['TotalPages'] = $this->totalPages; + $result['Results in this page'] = $this->resultsInThisPage; + + return "PagSeguroSearchResult: " . var_export($result, true); + + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroSender.class.php b/PagSeguroLibrary/domain/PagSeguroSender.class.php new file mode 100644 index 0000000..4014a79 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroSender.class.php @@ -0,0 +1,203 @@ +setName($data['name']); + } + if (isset($data['email'])) { + $this->setEmail($data['email']); + } + if (isset($data['phone']) && $data['phone'] instanceof PagSeguroPhone) { + $this->setPhone($data['phone']); + } else if (isset($data['areaCode']) && isset($data['number'])) { + $phone = new PagSeguroPhone($data['areaCode'], $data['number']); + $this->setPhone($phone); + } + if (isset($data['documents']) && is_array($data['documents'])) { + $this->setDocuments($data['documents']); + } + if (isset($data['ip'])) { + $this->getIP(); + } + } + } + + /*** + * Sets the sender name + * @param String $name + */ + public function setName($name) + { + $this->name = PagSeguroHelper::formatString($name, 50, ''); + } + + /*** + * @return String the sender name + */ + public function getName() + { + return $this->name; + } + + /*** + * Sets the Sender e-mail + * @param email + */ + public function setEmail($email) + { + $this->email = $email; + } + + /*** + * @return String the sender e-mail + */ + public function getEmail() + { + return $this->email; + } + + /*** + * Sets the sender phone + * @param String $areaCode + * @param String $number + */ + public function setPhone($areaCode, $number = null) + { + $param = $areaCode; + if ($param instanceof PagSeguroPhone) { + $this->phone = $param; + } elseif ($number) { + $phone = new PagSeguroPhone(); + $phone->setAreaCode($areaCode); + $phone->setNumber($number); + $this->phone = $phone; + } + } + + /*** + * @return PagSeguroPhone the sender phone + * @see PagSeguroPhone + */ + public function getPhone() + { + return $this->phone; + } + + /*** + * Get Sender documents + * @return array PagSeguroDocument List of PagSeguroDocument + * @see PagSeguroDocument + */ + public function getDocuments() + { + return $this->documents; + } + + /*** + * Set PagSeguro documents + * @param array $documents + * @see PagSeguroDocument + */ + public function setDocuments(array $documents) + { + if (count($documents) > 0) { + foreach ($documents as $document) { + if ($document instanceof PagSeguroSenderDocument) { + $this->documents[] = $document; + } else if (is_array($document)) { + $this->addDocument($document['type'], $document['value']); + } + } + } + } + + /*** + * Add a document for Sender object + * @param String $type + * @param String $value + */ + public function addDocument($type, $value) + { + if ($type && $value) { + if (count($this->documents) == 0) { + $document = new PagSeguroSenderDocument($type, $value); + $this->documents[] = $document; + } + } + } + + /*** + * Add an ip for Sender object + */ + public function getIP() + { + if (function_exists('apache_request_headers')) { + $headers = apache_request_headers(); + } else { + $headers = $_SERVER; + } + + if (array_key_exists('X-Forwarded-For', $headers) + && filter_var($headers['X-Forwarded-For'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4) ) { + $ip = $headers['X-Forwarded-For']; + + } elseif (array_key_exists('HTTP_X_FORWARDED_FOR', $headers) + && filter_var($headers['HTTP_X_FORWARDED_FOR'], FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) { + $ip = $headers['HTTP_X_FORWARDED_FOR']; + + } else { + $ip = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP); + } + + $this->ip = $ip; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroSenderDocument.class.php b/PagSeguroLibrary/domain/PagSeguroSenderDocument.class.php new file mode 100644 index 0000000..12c7beb --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroSenderDocument.class.php @@ -0,0 +1,102 @@ +setType($type); + $this->setValue($value); + } + } + + /*** + * Get document type + * @return string + */ + public function getType() + { + return $this->type; + } + + /*** + * Set document type + * @param string $type + */ + public function setType($type) + { + $this->type = strtoupper($type); + } + + /*** + * Get document value + * @return string + */ + public function getValue() + { + return $this->value; + } + + /*** + * Set document value + * @param string $value + */ + public function setValue($value) + { + $this->value = PagSeguroHelper::getOnlyNumbers($value); + } + + /*** + * Gets toString class + * @return string + */ + public function toString() + { + $document = array(); + $document['type'] = $this->type; + $document['value'] = $this->value; + + return "PagSeguroSenderDocument: " . var_export($document, true); + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroSession.class.php b/PagSeguroLibrary/domain/PagSeguroSession.class.php new file mode 100644 index 0000000..40a52c6 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroSession.class.php @@ -0,0 +1,66 @@ +id; + } + + /*** + * Sets the session id + * + * @param string id + */ + public function setId($id) + { + $this->id = $id; + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + $session = array(); + $session['id'] = $this->id; + + $session = "Session: " . var_export($session, true); + + return $session; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroShipping.class.php b/PagSeguroLibrary/domain/PagSeguroShipping.class.php new file mode 100644 index 0000000..d828f8b --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroShipping.class.php @@ -0,0 +1,119 @@ +address = $data['address']; + } + if (isset($data['type']) && $data['type'] instanceof PagSeguroShippingType) { + $this->type = $data['type']; + } + if (isset($data['cost'])) { + $this->cost = $data['cost']; + } + } + } + + /*** + * Sets the shipping address + * @see PagSeguroAddress + * @param PagSeguroAddress $address + */ + public function setAddress(PagSeguroAddress $address) + { + $this->address = $address; + } + + /*** + * @return PagSeguroAddress the shipping Address + * @see PagSeguroAddress + */ + public function getAddress() + { + return $this->address; + } + + /*** + * Sets the shipping type + * @param PagSeguroShippingType $type + * @see PagSeguroShippingType + */ + public function setType(PagSeguroShippingType $type) + { + $this->type = $type; + } + + /*** + * @return PagSeguroShippingType the shipping type + * @see PagSeguroShippingType + */ + public function getType() + { + return $this->type; + } + + /*** + * @param $cost float + */ + public function setCost($cost) + { + $this->cost = $cost; + } + + /*** + * @return float the shipping cost + */ + public function getCost() + { + return $this->cost; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroShippingType.class.php b/PagSeguroLibrary/domain/PagSeguroShippingType.class.php new file mode 100644 index 0000000..e82c656 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroShippingType.class.php @@ -0,0 +1,119 @@ + 1, + 'SEDEX' => 2, + 'NOT_SPECIFIED' => 3 + ); + + /*** + * the shipping type value + * Example: 1 + */ + private $value; + + /*** + * @param null $value + */ + public function __construct($value = null) + { + if ($value) { + $this->value = $value; + } + } + + /*** + * @param $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /*** + * @param $type + * @throws Exception + */ + public function setByType($type) + { + if (isset(self::$typeList[$type])) { + $this->value = self::$typeList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + /*** + * @return int the value of the shipping type + */ + public function getValue() + { + return $this->value; + } + + /*** + * @param value + * @return PagSeguroShippingType the PagSeguroShippingType corresponding to the informed value + */ + public function getTypeFromValue($value = null) + { + $value = ($value === null ? $this->value : $value); + return array_search($value, self::$typeList); + } + + /*** + * @param string + * @return integer the code corresponding to the informed shipping type + */ + public static function getCodeByType($type) + { + if (isset(self::$typeList[$type])) { + return self::$typeList[$type]; + } else { + return false; + } + } + + /*** + * @param string $type + * @return PagSeguroShippingType a PagSeguroShippingType object corresponding to the informed type + */ + public static function createByType($type) + { + $ShippingType = new PagSeguroShippingType(); + $ShippingType->setByType($type); + return $ShippingType; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroTransaction.class.php b/PagSeguroLibrary/domain/PagSeguroTransaction.class.php new file mode 100644 index 0000000..1e325f8 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroTransaction.class.php @@ -0,0 +1,605 @@ +lastEventDate; + } + + /*** + * Sets the last event date + * + * @param lastEventDate + */ + public function setLastEventDate($lastEventDate) + { + $this->lastEventDate = $lastEventDate; + } + + /*** + * @return datetime the transaction date + */ + public function getDate() + { + return $this->date; + } + + /*** + * Sets the transaction date + * + * @param string date + */ + public function setDate($date) + { + $this->date = $date; + } + + /*** + * @return string the transaction code + */ + public function getCode() + { + return $this->code; + } + + /*** + * Sets the transaction code + * + * @param code + */ + public function setCode($code) + { + $this->code = $code; + } + + /*** + * You can use the reference code to store an identifier so you can + * associate the PagSeguro transaction to a transaction in your system. + * + * @return string the reference code + */ + public function getReference() + { + return $this->reference; + } + + /*** + * Sets the reference code + * + * @param reference + */ + public function setReference($reference) + { + $this->reference = $reference; + } + + /*** + * @return string the recovery code + */ + public function getRecoveryCode() + { + return $this->recoveryCode; + } + + /*** + * Sets the recovery code + * + * @param code + */ + public function setRecoveryCode($recoveryCode) + { + $this->recoveryCode = $recoveryCode; + } + + /*** + * @return PagSeguroTransactionType the transaction type + * @see PagSeguroTransactionType + */ + public function getType() + { + return $this->type; + } + + /*** + * Sets the transaction type + * @param PagSeguroTransactionType $type + */ + public function setType(PagSeguroTransactionType $type) + { + $this->type = $type; + } + + /*** + * @return PagSeguroTransactionStatus the transaction status + * @see PagSeguroTransactionStatus + */ + public function getStatus() + { + return $this->status; + } + + /*** + * Sets the transaction status + * @param PagSeguroTransactionStatus $status + */ + public function setStatus(PagSeguroTransactionStatus $status) + { + $this->status = $status; + } + + /** + * @return PagSeguroTransactionCancellationSource the transaction cancellation source + * @see PagSeguroTransactionCancellationSource + */ + public function getCancellationSource() + { + return $this->cancellationSource; + } + + /** + * Sets the transaction cancellation source + * @param PagSeguroTransactionCancellationSource $cancellationSource + */ + public function setCancellationSource(PagSeguroTransactionCancellationSource $cancellationSource) + { + $this->cancellationSource = $cancellationSource; + } + + /*** + * @return PagSeguroPaymentMethod the payment method used in this transaction + * @see PagSeguroPaymentMethod + */ + public function getPaymentMethod() + { + return $this->paymentMethod; + } + + /*** + * Sets the payment link used in this transaction + * @param url $paymentLink + */ + public function setPaymentLink($paymentLink) + { + $this->paymentLink = $paymentLink; + } + + /*** + * @return the payment link method used in this transaction + */ + public function getPaymentLink() + { + return $this->paymentLink; + } + + /*** + * Sets the payment method used in this transaction + * @param PagSeguroPaymentMethod $paymentMethod + */ + public function setPaymentMethod(PagSeguroPaymentMethod $paymentMethod) + { + $this->paymentMethod = $paymentMethod; + } + + /*** + * @return float the transaction gross amount + */ + public function getGrossAmount() + { + return $this->grossAmount; + } + + /*** + * Sets the transaction gross amount + * @param float $totalValue + */ + public function setGrossAmount($totalValue) + { + $this->grossAmount = $totalValue; + } + + /*** + * @return float the transaction gross amount + */ + public function getDiscountAmount() + { + return $this->discountAmount; + } + + /*** + * Sets the transaction gross amount + * @param float $discountAmount + */ + public function setDiscountAmount($discountAmount) + { + $this->discountAmount = $discountAmount; + } + + /*** + * @return float the fee amount + */ + public function getFeeAmount() + { + return $this->feeAmount; + } + + /*** + * Sets the transaction fee amount + * @param float $feeAmount + */ + public function setFeeAmount($feeAmount) + { + $this->feeAmount = $feeAmount; + } + + /*** + * @return float the net amount + */ + public function getNetAmount() + { + return $this->netAmount; + } + + /*** + * Sets the net amount + * @param float $netAmount + */ + public function setNetAmount($netAmount) + { + $this->netAmount = $netAmount; + } + + /*** + * @return date the escrow end date + */ + public function getEscrowEndDate() + { + return $this->escrowEndDate; + } + + /*** + * Sets the escrow end date + * @param date $escrowEndDate + */ + public function setEscrowEndDate($escrowEndDate) + { + $this->escrowEndDate = $escrowEndDate; + } + + /*** + * @return float the extra amount + */ + public function getExtraAmount() + { + return $this->extraAmount; + } + + /*** + * Sets the extra amount + * @param float $extraAmount + */ + public function setExtraAmount($extraAmount) + { + $this->extraAmount = $extraAmount; + } + + /*** + * @return integer the installment count + */ + public function getInstallmentCount() + { + return $this->installmentCount; + } + + /*** + * Sets the installment count + * @param integer $installmentCount + */ + public function setInstallmentCount($installmentCount) + { + $this->installmentCount = $installmentCount; + } + + /*** + * Sets the transaction creditorFees + * @param float $creditorFees + */ + public function setCreditorFees($creditorFees) + { + $this->creditorFees = $creditorFees; + } + + /*** + * @return object the transaction creditor fees + */ + public function getCreditorFees() + { + return $this->creditorFees; + } + + /*** + * Sets the transaction Operational Fee Amount + * @param float $operationalFeeAmount + */ + public function setOperationalFeeAmount($operationalFeeAmount) + { + $this->operationalFeeAmount = $operationalFeeAmount; + } + + /*** + * @return float the transaction operational fee amount + */ + public function getOperationalFeeAmount() + { + return $this->operationalFeeAmount; + } + + /*** + * Sets the transaction Installment Fee Amount + * @param float $installmentFeeAmount + */ + public function setInstallmentFeeAmount($installmentFeeAmount) + { + $this->installmentFeeAmount = $installmentFeeAmount; + } + + /*** + * @return float the transaction installment fee amount + */ + public function getInstallmentFeeAmount() + { + return $this->installmentFeeAmount; + } + + /*** + * @return array PagSeguroItem the items/products list in this transaction + * @see PagSeguroItem + */ + public function getItems() + { + return $this->items; + } + + /*** + * Sets the list of items/products in this transaction + * @param array $items + * @see PagSeguroItem + */ + public function setItems(array $items) + { + $this->items = $items; + } + + /*** + * @return integer the items/products count in this transaction + */ + public function getItemCount() + { + return $this->items == null ? null : count($this->items); + } + + /*** + * @return PagSeguroSender the sender information, who is sending money in this transaction + * @see PagSeguroSender + */ + public function getSender() + { + return $this->sender; + } + + /*** + * Sets the sender information, who is sending money in this transaction + * @param PagSeguroSender $sender + */ + public function setSender(PagSeguroSender $sender) + { + $this->sender = $sender; + } + + /*** + * @return PagSeguroShipping the shipping information + * @see PagSeguroShipping + */ + public function getShipping() + { + return $this->shipping; + } + + /*** + * sets the shipping information for this transaction + * @param PagSeguroShipping $shipping + */ + public function setShipping(PagSeguroShipping $shipping) + { + $this->shipping = $shipping; + } + + /*** + * @return String a string that represents the current object + */ + public function toString() + { + + $transaction = array(); + $transaction['code'] = $this->code; + $transaction['email'] = $this->sender ? $this->sender->getEmail() : "null"; + $transaction['date'] = $this->date; + $transaction['reference'] = $this->reference; + $transaction['status'] = $this->status ? $this->status->getValue() : "null"; + $transaction['itemsCount'] = is_array($this->items) ? count($this->items) : "null"; + + $transaction = "Transaction: " . var_export($transaction, true); + + return $transaction; + + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroTransactionCancellationSource.class.php b/PagSeguroLibrary/domain/PagSeguroTransactionCancellationSource.class.php new file mode 100644 index 0000000..f7bc326 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroTransactionCancellationSource.class.php @@ -0,0 +1,103 @@ + "INTERNAL", + 'FINANCEIRA' => "EXTERNAL" + ); + + /*** + * the value of the transaction cancellation source + * Example: EXTERNAL + */ + private $value; + + /*** + * @param null $value + */ + public function __construct($value = null) + { + if ($value) { + $this->value = $value; + } + } + + /*** + * @param $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /*** + * @param $type + * @throws Exception + */ + public function setByType($type) + { + if (isset(self::$sourceList[$type])) { + $this->value = self::$sourceList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + /*** + * @return string the status value. + */ + public function getValue() + { + return $this->value; + } + + /*** + * @param value + * @return String the transaction cancellation source corresponding to the informed source value + */ + public function getTypeFromValue($value = null) + { + $value = ($value == null ? $this->value : $value); + return array_search($this->value, self::$sourceList); + } + + /*** + * Get status list + * @return array + */ + public static function getSourceList() + { + return self::$sourceList; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroTransactionCreditorFees.class.php b/PagSeguroLibrary/domain/PagSeguroTransactionCreditorFees.class.php new file mode 100644 index 0000000..0edf4d2 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroTransactionCreditorFees.class.php @@ -0,0 +1,80 @@ +setIntermediationRateAmount($value['intermediationRateAmount']); + $this->setIntermediationFeeAmount($value['intermediationFeeAmount']); + } + } + + /*** + * Sets the transaction intermediation Rate Amount + * @param float $intermediationRateAmount + */ + public function setIntermediationRateAmount($intermediationRateAmount) + { + $this->intermediationRateAmount = $intermediationRateAmount; + } + + /*** + * @return float the transaction intermediation Rate Amount + */ + public function getIntermediationRateAmount() + { + return $this->intermediationRateAmount; + } + + /*** + * Sets the transaction intermediation Fee Amount + * @param float $intermediationFeeAmount + */ + public function setIntermediationFeeAmount($intermediationFeeAmount) + { + $this->intermediationFeeAmount = $intermediationFeeAmount; + } + + /*** + * @return float the transaction intermediation Fee Amount + */ + public function getIntermediationFeeAmount() + { + return $this->intermediationFeeAmount; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroTransactionSearchResult.class.php b/PagSeguroLibrary/domain/PagSeguroTransactionSearchResult.class.php new file mode 100644 index 0000000..aa5c047 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroTransactionSearchResult.class.php @@ -0,0 +1,53 @@ +transactions; + } + + /*** + * Sets the transaction summaries in this page + * + * @param array $transactions + */ + public function setTransactions(array $transactions) + { + $this->transactions = $transactions; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroTransactionStatus.class.php b/PagSeguroLibrary/domain/PagSeguroTransactionStatus.class.php new file mode 100644 index 0000000..483e724 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroTransactionStatus.class.php @@ -0,0 +1,111 @@ + 0, + 'WAITING_PAYMENT' => 1, + 'IN_ANALYSIS' => 2, + 'PAID' => 3, + 'AVAILABLE' => 4, + 'IN_DISPUTE' => 5, + 'REFUNDED' => 6, + 'CANCELLED' => 7, + 'SELLER_CHARGEBACK' => 8, + 'CONTESTATION' => 9 + ); + + /*** + * the value of the transaction status + * Example: 3 + */ + private $value; + + /*** + * @param null $value + */ + public function __construct($value = null) + { + if ($value) { + $this->value = $value; + } + } + + /*** + * @param $value + */ + public function setValue($value) + { + $this->value = $value; + } + + /*** + * @param $type + * @throws Exception + */ + public function setByType($type) + { + if (isset(self::$statusList[$type])) { + $this->value = self::$statusList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + /*** + * @return integer the status value. + */ + public function getValue() + { + return $this->value; + } + + /*** + * @param value + * @return String the transaction status corresponding to the informed status value + */ + public function getTypeFromValue($value = null) + { + $value = ($value == null ? $this->value : $value); + return array_search($this->value, self::$statusList); + } + + /*** + * Get status list + * @return array + */ + public static function getStatusList() + { + return self::$statusList; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroTransactionSummary.class.php b/PagSeguroLibrary/domain/PagSeguroTransactionSummary.class.php new file mode 100644 index 0000000..83c8f82 --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroTransactionSummary.class.php @@ -0,0 +1,353 @@ +date; + } + + /*** + * Sets the transaction date + * @param String $date + */ + public function setDate($date) + { + $this->date = $date; + } + + /*** + * @return the transaction code + */ + public function getCode() + { + return $this->code; + } + + /*** + * Sets transaction code + * @param String $code + */ + public function setCode($code) + { + $this->code = $code; + } + + /*** + * You can use the reference code to store an identifier so you can + * associate the PagSeguro transaction to a transaction in your system. + * + * @return the reference code + */ + public function getReference() + { + return $this->reference; + } + + /*** + * Sets the reference code + * + * @param reference + */ + public function setReference($reference) + { + $this->reference = $reference; + } + + /*** + * @return the transaction gross amount + */ + public function getGrossAmount() + { + return $this->grossAmount; + } + + /*** + * Sets the gorss amount + * @param float $grossAmount + */ + public function setGrossAmount($grossAmount) + { + $this->grossAmount = $grossAmount; + } + + /*** + * @return the transaction type + * @see PagSeguroTransactionType + */ + public function getType() + { + return $this->type; + } + + /*** + * Sets the transaction sype + * @param PagSeguroTransactionType $type + */ + public function setType(PagSeguroTransactionType $type) + { + $this->type = $type; + } + + /*** + * Date the last notification about this transaction was sent + * @return the last event date + */ + public function getLastEventDate() + { + return $this->lastEventDate; + } + + /*** + * Sets the last event date + * @param String $lastEventDate + */ + public function setLastEventDate($lastEventDate) + { + $this->lastEventDate = $lastEventDate; + } + + /*** + * @return the transaction status + * @see PagSeguroTransactionStatus + */ + public function getStatus() + { + return $this->status; + } + + /*** + * Sets the transaction status + * @param PagSeguroTransactionStatus $status + */ + public function setStatus(PagSeguroTransactionStatus $status) + { + $this->status = $status; + } + + /*** + * @return the net amount + */ + public function getNetAmount() + { + return $this->netAmount; + } + + /*** + * Sets the net amount + * @param float $netAmount + */ + public function setNetAmount($netAmount) + { + $this->netAmount = $netAmount; + } + + /*** + * @return the discount amount + */ + public function getDiscountAmount() + { + return $this->discountAmount; + } + + /*** + * Sets the discount amount + * @param float $discountAmount + */ + public function setDiscountAmount($discountAmount) + { + $this->discountAmount = $discountAmount; + } + + /*** + * @return the fee amount + */ + public function getFeeAmount() + { + return $this->feeAmount; + } + + /*** + * Sets the fee amount + * @param float $feeAmount + */ + public function setFeeAmount($feeAmount) + { + $this->feeAmount = $feeAmount; + } + + /*** + * @return the extra amount + */ + public function getExtraAmount() + { + return $this->extraAmount; + } + + /*** + * Sets the extra amount + * @param float $extraAmount + */ + public function setExtraAmount($extraAmount) + { + $this->extraAmount = $extraAmount; + } + + /*** + * Sets the cancellation source + * @param PagSeguroTransactionCancellationSource $cancellationSource + */ + public function setCancellationSource(PagSeguroTransactionCancellationSource $cancellationSource) + { + $this->cancellationSource = $cancellationSource; + } + + /** + * @return the cancellation source + * @see PagSeguroTransactionCancellationSource + */ + public function getCancellationSource() + { + return $this->cancellationSource; + } + + /** + * Sets the payment method + * @param PagSeguroPaymentMethod $paymentMethod + */ + public function setPaymentMethod(PagSeguroPaymentMethod $paymentMethod) + { + $this->paymentMethod = $paymentMethod; + } + + /*** + * @return the payment method + * @see PagSeguroPaymentMethod + */ + public function getPaymentMethod() + { + return $this->paymentMethod; + } + + /*** + * @return the recovery code + */ + public function getRecoveryCode() + { + return $this->recoveryCode; + } + + /*** + * Sets the recovery code + * @param string $recoveryCode + */ + public function setRecoveryCode($recoverycode) + { + $this->recoveryCode = $recoverycode; + } +} diff --git a/PagSeguroLibrary/domain/PagSeguroTransactionType.class.php b/PagSeguroLibrary/domain/PagSeguroTransactionType.class.php new file mode 100644 index 0000000..cceaddc --- /dev/null +++ b/PagSeguroLibrary/domain/PagSeguroTransactionType.class.php @@ -0,0 +1,82 @@ + 1, + 'TRANSFER' => 2, + 'FUND_ADDITION' => 3, + 'WITHDRAW' => 4, + 'CHARGE' => 5, + 'DONATION' => 6, + 'BONUS' => 7, + 'BONUS_REPASS' => 8, + 'OPERATIONAL' => 9, + 'POLITICAL_DONATION' => 10 + ); + + private $value; + + public function __construct($value = null) + { + if ($value) { + $this->value = $value; + } + } + + public function setValue($value) + { + $this->value = $value; + } + + public function setByType($type) + { + if (isset(self::$typeList[$type])) { + $this->value = self::$typeList[$type]; + } else { + throw new Exception("undefined index $type"); + } + } + + public function getValue() + { + return $this->value; + } + + /*** + * @param integer|string $value + * @return string|integer the transaction type corresponding to the informed type value value + */ + public function getTypeFromValue($value = null) + { + $value = ($value == null ? $this->value : $value); + return array_search($value, self::$typeList); + } +} diff --git a/PagSeguroLibrary/exception/PagSeguroServiceException.class.php b/PagSeguroLibrary/exception/PagSeguroServiceException.class.php new file mode 100644 index 0000000..14c6bbf --- /dev/null +++ b/PagSeguroLibrary/exception/PagSeguroServiceException.class.php @@ -0,0 +1,136 @@ +httpStatus = $httpStatus; + if ($errors) { + $this->errors = $errors; + } + //$this->httpMessage = $this->getFormattedMessage(); + parent::__construct($this->getOneLineMessage()); + } + + /*** + * @return array + */ + public function getErrors() + { + return $this->errors; + } + + /*** + * @param array $errors + */ + public function setErrors(array $errors) + { + $this->errors = $errors; + } + + /*** + * @return PagSeguroHttpStatus + */ + public function getHttpStatus() + { + return $this->httpStatus; + } + + /*** + * @param PagSeguroHttpStatus $httpStatus + */ + public function setHttpStatus(PagSeguroHttpStatus $httpStatus) + { + $this->httpStatus = $httpStatus; + } + + /*** + * @return string + */ + private function getHttpMessage() + { + + switch ($type = $this->httpStatus->getType()) { + case 'BAD_REQUEST': + case 'UNAUTHORIZED': + case 'FORBIDDEN': + case 'NOT_FOUND': + case 'INTERNAL_SERVER_ERROR': + case 'BAD_GATEWAY': + $message = $type; + break; + default: + $message = "UNDEFINED"; + break; + } + return $message; + } + + /*** + * @return string + */ + public function getFormattedMessage() + { + $message = ""; + $message .= "[HTTP " . $this->httpStatus->getStatus() . "] - " . $this->getHttpMessage() . "\n"; + foreach ($this->errors as $key => $value) { + if ($value instanceof PagSeguroError) { + $message .= "$key [" . $value->getCode() . "] - " . $value->getMessage(); + } + } + return $message; + } + + /*** + * @return mixed + */ + public function getOneLineMessage() + { + return str_replace("\n", " ", $this->getFormattedMessage()); + } +} diff --git a/PagSeguroLibrary/helper/PagSeguroHelper.class.php b/PagSeguroLibrary/helper/PagSeguroHelper.class.php new file mode 100644 index 0000000..d5803fd --- /dev/null +++ b/PagSeguroLibrary/helper/PagSeguroHelper.class.php @@ -0,0 +1,175 @@ +format($format); + } elseif (is_numeric($date)) { + $d = date($format, $date); + } else { + $d = (string) $date; + } + return $d; + } + + /*** + * @param $value + * @return string + */ + public static function decimalFormat($value) + { + if (is_int($value)) { + return $value; + }else if (is_float($value)) { + if (strcspn(strrev($value), '.') >= 3) { + $value = floor($value * 100) / 100; + } + } + return (string)number_format($value, 2, '.', ''); + } + + /*** + * @param $date + * @param $days + * @return bool|string + */ + public static function subDays($date, $days) + { + $d = self::formatDate($date); + $d = date_parse($d); + $d = mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'] - $days, $d['year']); + return self::formatDate($d); + } + + /*** + * @param $var + * @param null $dump + */ + public static function printError($var, $dump = null) + { + if (is_array($var) || is_object($var)) { + echo "
";
+            if ($dump) {
+                var_dump($var);
+            } else {
+                print_r($var);
+            }
+            echo "
"; + } + } + + /*** + * Remove left, right and inside extra spaces in string + * @param string $string + * @return string + */ + public static function removeStringExtraSpaces($string) + { + return trim(preg_replace("/( +)/", " ", $string)); + } + + /*** + * Perform truncate of string value + * @param string $string + * @param int $limit + * @param mixed $endchars + * @return string + */ + public static function truncateValue($string, $limit, $endchars = '...') + { + + if (!is_array($string) && !is_object($string)) { + $stringLength = strlen($string); + $endcharsLength = strlen($endchars); + + if ($stringLength > (int) $limit) { + $cut = (int) ($limit - $endcharsLength); + $string = substr($string, 0, $cut) . $endchars; + } + } + return $string; + } + + /*** + * Return formatted string to send in PagSeguro request + * @param string $string + * @param int $limit + * @param mixed $endchars + * @return string + */ + public static function formatString($string, $limit, $endchars = '...') + { + $string = PagSeguroHelper::removeStringExtraSpaces($string); + return PagSeguroHelper::truncateValue($string, $limit, $endchars); + } + + /*** + * Check if var is empty + * @param string $value + * @return boolean + */ + public static function isEmpty($value) + { + return (!isset($value) || trim($value) == ""); + } + + /*** + * Check if notification post is empty + * @param array $notification_data + * @return boolean + */ + public static function isNotificationEmpty(array $notification_data) + { + $isEmpty = true; + + if (isset($notification_data['notificationCode']) && isset($notification_data['notificationType'])) { + $isEmpty = (PagSeguroHelper::isEmpty($notification_data['notificationCode']) || + PagSeguroHelper::isEmpty($notification_data['notificationType']) + ); + } + + return $isEmpty; + } + + /*** + * Remove all non digit character from string + * @param string $value + * @return string + */ + public static function getOnlyNumbers($value) + { + return preg_replace('/\D/', '', $value); + } +} diff --git a/PagSeguroLibrary/loader/PagSeguroAutoLoader.class.php b/PagSeguroLibrary/loader/PagSeguroAutoLoader.class.php new file mode 100644 index 0000000..8b6baca --- /dev/null +++ b/PagSeguroLibrary/loader/PagSeguroAutoLoader.class.php @@ -0,0 +1,73 @@ + $dir) { + $file = PagSeguroLibrary::getPath() . DIRECTORY_SEPARATOR . + $dir . DIRECTORY_SEPARATOR . $class . '.class.php'; + if (file_exists($file) && is_file($file)) { + require_once $file; + } + } + } +} diff --git a/PagSeguroLibrary/log/LogPagSeguro.class.php b/PagSeguroLibrary/log/LogPagSeguro.class.php new file mode 100644 index 0000000..5b1194c --- /dev/null +++ b/PagSeguroLibrary/log/LogPagSeguro.class.php @@ -0,0 +1,210 @@ +getMessage() . " - Can't create log file. Permission denied. File location: " . + self::$fileLocation; + return false; + } + + } + + /*** + * Prints a info message in the log file + * @param String $message + */ + public static function info($message) + { + self::logMessage($message, 'info'); + } + + /*** + * Prints a warning message in the log file + * @param String $message + */ + public static function warning($message) + { + self::logMessage($message, 'warning'); + } + + /*** + * Prints an error message in the log file + * @param String $message + */ + public static function error($message) + { + self::logMessage($message, 'error'); + } + + /*** + * Prints a debug message in the log file + * @param String $message + */ + public static function debug($message) + { + self::logMessage($message, 'debug'); + } + + /*** + * Logs a message + * @param String $message + * @param String $type + * @throws Exception + * @return void|boolean + */ + private static function logMessage($message, $type = null) + { + if (!self::$active) { + return; + } + + try { + $file = fopen(self::$fileLocation, "a"); + + if (!$file) { + throw new Exception('Unable to open the input file'); + } + + $date_message = "{" . @date("Y/m/d H:i:s", time()) . "}"; + + switch ($type) { + case 'info': + $type_message = "[Info]"; + break; + case 'warning': + $type_message = "[Warning]"; + break; + case 'error': + $type_message = "[Error]"; + break; + case 'debug': + default: + $type_message = "[Debug]"; + break; + } + $str = "$date_message $type_message $message"; + fwrite($file, "$str \r\n"); + fclose($file); + + } catch (Exception $e) { + echo $e->getMessage() . " - Can't create log file. Permission denied. File location: " . + self::$fileLocation; + } + + } + + /*** + * Retrieves the log messages + * @param integer $negativeOffset + * @param boolean|string $reverse + * + * @return boolean|string + */ + public static function getHtml($negativeOffset = null, $reverse = null) + { + if (!self::$active) { + return false; + } + if (file_exists(self::$fileLocation) && $file = file(self::$fileLocation)) { + if ($negativeOffset !== null) { + $file = array_slice($file, (-$negativeOffset), null, true); + } + if ($reverse) { + $file = array_reverse($file, true); + } + $content = ""; + foreach ($file as $key => $value) { + $html = ("

" . str_replace("\n", "
", $value) . "

"); + $html = str_replace("[", "", $html); + $html = str_replace("]", "", $html); + $html = str_replace("{", "", $html); + $html = str_replace("}", "", $html); + $content .= $html; + } + } + return isset($content) ? $content : false; + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroAuthorizationParser.class.php b/PagSeguroLibrary/parser/PagSeguroAuthorizationParser.class.php new file mode 100644 index 0000000..ab2dcbf --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroAuthorizationParser.class.php @@ -0,0 +1,219 @@ +getReference() != null) { + $data['reference'] = $authorization->getReference(); + } + // RedirectURL + if ($authorization->getRedirectURL() != null) { + $data['redirectURL'] = $authorization->getRedirectURL(); + } + // NotificationURL + if ($authorization->getNotificationURL() != null) { + $data['notificationURL'] = $authorization->getNotificationURL(); + } + // Permissions + if ($authorization->getPermissions()->getPermissions() != null) { + $data['permissions'] = implode(',', $authorization->getPermissions()->getPermissions()); + } + + // parameter + if (count($authorization->getParameter()->getItems()) > 0) { + foreach ($authorization->getParameter()->getItems() as $item) { + if ($item instanceof PagSeguroParameterItem) { + if (!PagSeguroHelper::isEmpty($item->getKey()) && !PagSeguroHelper::isEmpty($item->getValue())) { + if (!PagSeguroHelper::isEmpty($item->getGroup())) { + $data[$item->getKey() . '' . $item->getGroup()] = $item->getValue(); + } else { + $data[$item->getKey()] = $item->getValue(); + } + } + } + } + } + + return $data; + } + + /*** + * @param $str_xml + * @return PagSeguroAuthorization + */ + public static function readAuthorization($str_xml) + { + // Parser + $parser = new PagSeguroXmlParser($str_xml); + + return self::buildAuthorization( + new PagSeguroAuthorization(), + $parser->getResult('authorization') + ); + } + + /*** + * @param $str_xml + * @return PagSeguroAuthorization + */ + public static function readSearchResult($str_xml) + { + // Parser + $parser = new PagSeguroXmlParser($str_xml); + + $authorization = new PagSeguroAuthorizationSearchResult(); + + // + $data = $parser->getResult('authorizationSearchResult'); + + // + if (isset($data["date"])) { + $authorization->setDate($data['date']); + } + + // + if (isset($data['authorizations']) && is_array($data['authorizations'])) { + if (isset($data['authorizations']['authorization']) + && $data["resultsInThisPage"] > 1) { + $i = 0; + foreach ($data['authorizations']['authorization'] as $key => $value) { + $newAuthorization = new PagSeguroAuthorization(); + $nAuthorization[$i++] = self::buildAuthorization($newAuthorization, $value); + } + $authorization->setAuthorizations($nAuthorization); + + } else { + $newAuthorization = new PagSeguroAuthorization(); + $authorization->setAuthorizations( + self::buildAuthorization( + $newAuthorization, + $data['authorizations']['authorization'] + ) + ); + } + + } + + // + if (isset($data["resultsInThisPage"])) { + $authorization->setResultsInThisPage($data['resultsInThisPage']); + } + // + if (isset($data["totalPages"])) { + $authorization->setTotalPages($data['totalPages']); + } + // + if (isset($data["currentPage"])) { + $authorization->setCurrentPage($data["currentPage"]); + } + + return $authorization; + } + + /** + * @param PagSeguroAuthorization $authorization + * @param $data + */ + private static function buildAuthorization(PagSeguroAuthorization $authorization, $data) + { + // + if (isset($data["code"])) { + $authorization->setCode($data['code']); + } + + // + if (isset($data["creationDate"])) { + $authorization->setCreationDate($data['creationDate']); + } + + // + if (isset($data["reference"])) { + $authorization->setReference($data['reference']); + } + + // + if (isset($data["account"]) and isset($data["account"]['publicKey'])) { + $authorization->setAccount(new PagSeguroAuthorizationAccount($data["account"]['publicKey'])); + } + + // + if (isset($data["permissions"])) { + if (isset($data["permissions"]["permission"])) { + foreach ($data["permissions"]["permission"] as $permission) { + $permissions[] = new PagSeguroAuthorizationPermission( + $permission['code'], + $permission['status'], + $permission['lastUpdate'] + ); + } + } + $permissions = new PagSeguroAuthorizationPermissions($permissions); + $authorization->setPermissions($permissions); + + return $authorization; + } + } + + /*** + * @param $str_xml + * @return PagSeguroParserData Success + */ + public static function readSuccessXml($str_xml) + { + $parser = new PagSeguroXmlParser($str_xml); + + $data = $parser->getResult('authorizationRequest'); + $authorizationParserData = new PagSeguroParserData(); + $authorizationParserData->setCode($data['code']); + $authorizationParserData->setRegistrationDate($data['date']); + return $authorizationParserData; + } + + /*** + * @param $error Authorization error + * @return object() + */ + private static function readError($error) + { + $err = new stdClass(); + $err->message = key($error); + $err->status = true; + + return $err; + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroCancelParser.class.php b/PagSeguroLibrary/parser/PagSeguroCancelParser.class.php new file mode 100644 index 0000000..39e9db9 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroCancelParser.class.php @@ -0,0 +1,39 @@ +getResult('result'); + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroDirectPaymentParser.class.php b/PagSeguroLibrary/parser/PagSeguroDirectPaymentParser.class.php new file mode 100644 index 0000000..2d14655 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroDirectPaymentParser.class.php @@ -0,0 +1,141 @@ +getPaymentMode() != null) { + $data["paymentMode"] = $payment->getPaymentMode()->getValue(); + } + + // paymentMethod + if ($payment->getPaymentMethod()->getPaymentMethod() != null) { + $data["paymentMethod"] = $payment->getPaymentMethod()->getPaymentMethod(); + } + + // senderHash + if ($payment->getSenderHash() != null) { + $data["senderHash"] = $payment->getSenderHash(); + } + + // receiverEmail + if ($payment->getReceiverEmail() != null) { + $data["receiverEmail"] = $payment->getReceiverEmail(); + } + + // Bank name + if ($payment->getOnlineDebit() != null) { + $data["bankName"] = $payment->getOnlineDebit()->getBankName(); + } + + //Credit Card + if ($payment->getCreditCard() != null) { + //Token + if ($payment->getCreditCard()->getToken() != null) { + $data['creditCardToken'] = $payment->getCreditCard()->getToken(); + } + + //Installments + if ($payment->getCreditCard()->getInstallment() != null) { + $installment = $payment->getCreditCard()->getInstallment(); + if ($installment->getQuantity() != null && $installment->getValue()) { + $data['installmentQuantity'] = $installment->getQuantity(); + $data['installmentValue'] = PagSeguroHelper::decimalFormat($installment->getValue()); + } + } + + //Holder + if ($payment->getCreditCard()->getHolder() != null) { + $holder = $payment->getCreditCard()->getHolder(); + if ($holder->getName() != null) { + $data['creditCardHolderName'] = $holder->getName(); + } + // documents + /*** @var $document PagSeguroDocument */ + if ($payment->getCreditCard()->getHolder()->getDocuments() != null) { + $documents = $payment->getCreditCard()->getHolder()->getDocuments(); + $data['creditCardHolderCPF'] = $documents->getValue(); + } + if ($holder->getBirthDate() != null) { + $data['creditCardHolderBirthDate'] = $holder->getBirthDate(); + } + // phone + if ($holder->getPhone() != null) { + if ($holder->getPhone()->getAreaCode() != null) { + $data['creditCardHolderAreaCode'] = $holder->getPhone()->getAreaCode(); + } + if ($holder->getPhone()->getNumber() != null) { + $data['creditCardHolderPhone'] = $holder->getPhone()->getNumber(); + } + } + } + + //Billing Address + if ($payment->getCreditCard()->getBilling() != null) { + $billingAddress = $payment->getCreditCard()->getBilling()->getAddress(); + if ($billingAddress->getStreet() != null) { + $data['billingAddressStreet'] = $billingAddress->getStreet(); + } + if ($billingAddress->getNumber() != null) { + $data['billingAddressNumber'] = $billingAddress->getNumber(); + } + if ($billingAddress->getComplement() != null) { + $data['billingAddressComplement'] = $billingAddress->getComplement(); + } + if ($billingAddress->getCity() != null) { + $data['billingAddressCity'] = $billingAddress->getCity(); + } + if ($billingAddress->getState() != null) { + $data['billingAddressState'] = $billingAddress->getState(); + } + if ($billingAddress->getDistrict() != null) { + $data['billingAddressDistrict'] = $billingAddress->getDistrict(); + } + if ($billingAddress->getPostalCode() != null) { + $data['billingAddressPostalCode'] = $billingAddress->getPostalCode(); + } + if ($billingAddress->getCountry() != null) { + $data['billingAddressCountry'] = $billingAddress->getCountry(); + } + } + + } + + return $data; + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroInstallmentParser.class.php b/PagSeguroLibrary/parser/PagSeguroInstallmentParser.class.php new file mode 100644 index 0000000..fe02754 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroInstallmentParser.class.php @@ -0,0 +1,79 @@ +errors)) { + $brand = key($arr->installments); + + foreach ($arr->installments->$brand as $key => $installment) { + $installment->cardBrand = $brand; + + $installments[] = new PagSeguroInstallments($installment); + } + + return $installments; + } else { + return self::readError($arr->errors); + } + } + + /*** + * @param $error Installment error + * @return object() + */ + private static function readError($error) + { + $err = new stdClass(); + $err->message = key($error); + $err->status = true; + + return $err; + } + + /*** + * @param $installments Installments + * @return object installments + */ + private static function decode($installments) + { + return json_decode($installments); + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroParserData.class.php b/PagSeguroLibrary/parser/PagSeguroParserData.class.php new file mode 100644 index 0000000..d6bf6b3 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroParserData.class.php @@ -0,0 +1,104 @@ +code; + } + + /*** + * @param $code + */ + public function setCode($code) + { + $this->code = $code; + } + + /*** + * @return mixed + */ + public function getRegistrationDate() + { + return $this->registrationDate; + } + + /*** + * @param $registrationDate + */ + public function setRegistrationDate($registrationDate) + { + $this->registrationDate = $registrationDate; + } + + /*** + * @return mixed + */ + public function getStatus() + { + return $this->status; + } + + /*** + * @param $status + */ + public function setStatus($status) + { + $this->status = $status; + } + + /** + * @return string + */ + public function toString() + { + + $data = array(); + $data['code'] = $this->code; + $data['registrationDate'] = $this->registrationDate; + $data['status'] = $this->status; + + return "ParserData: " . var_export($data, true); + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroPaymentParser.class.php b/PagSeguroLibrary/parser/PagSeguroPaymentParser.class.php new file mode 100644 index 0000000..627dc22 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroPaymentParser.class.php @@ -0,0 +1,283 @@ +getPreApproval() != null) { + $data = PagSeguroPreApprovalParser::getData($payment->getPreApproval()); + } + } + + // reference + if ($payment->getReference() != null) { + $data["reference"] = $payment->getReference(); + } + + // sender + if ($payment->getSender() != null) { + if ($payment->getSender()->getName() != null) { + $data['senderName'] = $payment->getSender()->getName(); + } + if ($payment->getSender()->getEmail() != null) { + $data['senderEmail'] = $payment->getSender()->getEmail(); + } + + // phone + if ($payment->getSender()->getPhone() != null) { + if ($payment->getSender()->getPhone()->getAreaCode() != null) { + $data['senderAreaCode'] = $payment->getSender()->getPhone()->getAreaCode(); + } + if ($payment->getSender()->getPhone()->getNumber() != null) { + $data['senderPhone'] = $payment->getSender()->getPhone()->getNumber(); + } + } + + // documents + /*** @var $document PagSeguroDocument */ + if ($payment->getSender()->getDocuments() != null) { + $documents = $payment->getSender()->getDocuments(); + if (is_array($documents) && count($documents) == 1) { + foreach ($documents as $document) { + if (!is_null($document)) { + $document->getType() == "CPF" ? + $data['senderCPF'] = $document->getValue() : + $data['senderCNPJ'] = $document->getValue(); + } + } + } + } + + if ($payment->getSender()->getIP() != null) { + $data['ip'] = $payment->getSender()->getIP(); + } + } + + // currency + if ($payment->getCurrency() != null) { + $data['currency'] = $payment->getCurrency(); + } + + // items + $items = $payment->getItems(); + if (count($items) > 0) { + $i = 0; + + foreach ($items as $key => $value) { + $i++; + if ($items[$key]->getId() != null) { + $data["itemId$i"] = $items[$key]->getId(); + } + if ($items[$key]->getDescription() != null) { + $data["itemDescription$i"] = $items[$key]->getDescription(); + } + if ($items[$key]->getQuantity() != null) { + $data["itemQuantity$i"] = $items[$key]->getQuantity(); + } + if ($items[$key]->getAmount() != null) { + $amount = PagSeguroHelper::decimalFormat($items[$key]->getAmount()); + $data["itemAmount$i"] = $amount; + } + if ($items[$key]->getWeight() != null) { + $data["itemWeight$i"] = $items[$key]->getWeight(); + } + if ($items[$key]->getShippingCost() != null) { + $data["itemShippingCost$i"] = PagSeguroHelper::decimalFormat($items[$key]->getShippingCost()); + } + } + } + + // extraAmount + if ($payment->getExtraAmount() != null) { + $data['extraAmount'] = PagSeguroHelper::decimalFormat($payment->getExtraAmount()); + } + + // shipping + if ($payment->getShipping() != null) { + if ($payment->getShipping()->getType() != null && $payment->getShipping()->getType()->getValue() != null) { + $data['shippingType'] = $payment->getShipping()->getType()->getValue(); + } + + if ($payment->getShipping()->getCost() != null && $payment->getShipping()->getCost() != null) { + $data['shippingCost'] = PagSeguroHelper::decimalFormat($payment->getShipping()->getCost()); + } + + // address + if ($payment->getShipping()->getAddress() != null) { + if ($payment->getShipping()->getAddress()->getStreet() != null) { + $data['shippingAddressStreet'] = $payment->getShipping()->getAddress()->getStreet(); + } + if ($payment->getShipping()->getAddress()->getNumber() != null) { + $data['shippingAddressNumber'] = $payment->getShipping()->getAddress()->getNumber(); + } + if ($payment->getShipping()->getAddress()->getComplement() != null) { + $data['shippingAddressComplement'] = $payment->getShipping()->getAddress()->getComplement(); + } + if ($payment->getShipping()->getAddress()->getCity() != null) { + $data['shippingAddressCity'] = $payment->getShipping()->getAddress()->getCity(); + } + if ($payment->getShipping()->getAddress()->getState() != null) { + $data['shippingAddressState'] = $payment->getShipping()->getAddress()->getState(); + } + if ($payment->getShipping()->getAddress()->getDistrict() != null) { + $data['shippingAddressDistrict'] = $payment->getShipping()->getAddress()->getDistrict(); + } + if ($payment->getShipping()->getAddress()->getPostalCode() != null) { + $data['shippingAddressPostalCode'] = $payment->getShipping()->getAddress()->getPostalCode(); + } + if ($payment->getShipping()->getAddress()->getCountry() != null) { + $data['shippingAddressCountry'] = $payment->getShipping()->getAddress()->getCountry(); + } + } + } + // maxAge + if ($payment->getMaxAge() != null) { + $data['maxAge'] = $payment->getMaxAge(); + } + // maxUses + if ($payment->getMaxUses() != null) { + $data['maxUses'] = $payment->getMaxUses(); + } + + // redirectURL + if ($payment->getRedirectURL() != null) { + $data['redirectURL'] = $payment->getRedirectURL(); + } + + // notificationURL + if ($payment->getNotificationURL() != null) { + $data['notificationURL'] = $payment->getNotificationURL(); + } + + // metadata + if (count($payment->getMetaData()->getItems()) > 0) { + $i = 0; + foreach ($payment->getMetaData()->getItems() as $item) { + if ($item instanceof PagSeguroMetaDataItem) { + if (!PagSeguroHelper::isEmpty($item->getKey()) && !PagSeguroHelper::isEmpty($item->getValue())) { + $i++; + $data['metadataItemKey' . $i] = $item->getKey(); + $data['metadataItemValue' . $i] = $item->getValue(); + + if (!PagSeguroHelper::isEmpty($item->getGroup())) { + $data['metadataItemGroup' . $i] = $item->getGroup(); + } + } + } + } + } + + // paymentMethodConfig + if (count($payment->getPaymentMethodConfig()->getConfig()) > 0) { + $i = 0; + foreach ($payment->getPaymentMethodConfig()->getConfig() as $config) { + if ($config instanceof PagSeguroPaymentMethodConfigItem) { + if (!PagSeguroHelper::isEmpty($config->getKey()) + && !PagSeguroHelper::isEmpty($config->getValue())) + { + $i++; + if (!PagSeguroHelper::isEmpty($config->getGroup())) { + $data['paymentMethodGroup' . $i] = $config->getGroup(); + } + $data['paymentMethodConfigKey' . $i . "_1"] = $config->getKey(); + $data['paymentMethodConfigValue' . $i . "_1"] = $config->getValue(); + } + } + } + } + + // AcceptedPaymentMethod + if (count($payment->getAcceptedPaymentMethod()->getConfig()) > 0) { + $i = 0; + foreach ($payment->getAcceptedPaymentMethod()->getConfig() as $acceptedPayment) { + if ($acceptedPayment instanceof PagSeguroAcceptPaymentMethod) { + $data['acceptPaymentMethodGroup'] = $acceptedPayment->getGroup(); + $data['acceptPaymentMethodName'] = $acceptedPayment->getName(); + } + if ($acceptedPayment instanceof PagSeguroExcludePaymentMethod) { + $data['excludePaymentMethodGroup'] = $acceptedPayment->getGroup(); + $data['excludePaymentMethodName'] = $acceptedPayment->getName(); + } + } + } + + // parameter + if (count($payment->getParameter()->getItems()) > 0) { + foreach ($payment->getParameter()->getItems() as $item) { + if ($item instanceof PagSeguroParameterItem) { + if (!PagSeguroHelper::isEmpty($item->getKey()) && !PagSeguroHelper::isEmpty($item->getValue())) { + if (!PagSeguroHelper::isEmpty($item->getGroup())) { + $data[$item->getKey() . '' . $item->getGroup()] = $item->getValue(); + } else { + $data[$item->getKey()] = $item->getValue(); + } + } + } + } + } + + return $data; + } + + /*** + * @param $str_xml + * @return PagSeguroPaymentParserData Success + */ + public static function readSuccessXml($str_xml) + { + $parser = new PagSeguroXmlParser($str_xml); + $data = $parser->getResult('checkout'); + $PaymentParserData = new PagSeguroParserData(); + $PaymentParserData->setCode($data['code']); + $PaymentParserData->setRegistrationDate($data['date']); + return $PaymentParserData; + } + + /*** + * @param $str_xml + * @return parsed transaction + */ + public static function readTransactionXml($str_xml) + { + $parser = new PagSeguroXmlParser($str_xml); + $data = $parser->getResult('transaction'); + $PaymentParserData = new PagSeguroParserData(); + $PaymentParserData->setCode($data['code']); + $PaymentParserData->setRegistrationDate($data['date']); + return $PaymentParserData; + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroPreApprovalParser.class.php b/PagSeguroLibrary/parser/PagSeguroPreApprovalParser.class.php new file mode 100644 index 0000000..aedfd81 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroPreApprovalParser.class.php @@ -0,0 +1,335 @@ + + * @copyright 2007-2014 PagSeguro Internet Ltda. + * @license http://www.apache.org/licenses/LICENSE-2.0 + */ + +/*** + * Class PagSeguroPreApprovalParser + */ +class PagSeguroPreApprovalParser +{ + + /** + * @param $payment + * @return mixed + */ + public static function getData($preApproval) + { + + $data = array(); + + if ($preApproval->getReviewURL() != null) { + $data["reviewURL"] = $preApproval->getReviewURL(); + } + + if ($preApproval->getRedirectURL() != null) { + $data["redirectURL"] = $preApproval->getRedirectURL(); + } + + if ($preApproval->getReference() != null) { + $data["reference"] = $preApproval->getReference(); + } + + if ($preApproval->getPreApprovalMaxTotalAmount() != null) { + $data["preApprovalMaxTotalAmount"] = $preApproval->getPreApprovalMaxTotalAmount(); + } + + if ($preApproval->getPreApprovalMaxAmountPerPeriod() != null) { + $data["preApprovalMaxAmountPerPeriod"] = $preApproval->getPreApprovalMaxAmountPerPeriod(); + } + + if ($preApproval->getPreApprovalInitialDate() != null) { + $data["preApprovalInitialDate"] = $preApproval->getPreApprovalInitialDate(); + } + + if ($preApproval->getPreApprovalFinalDate() != null) { + $data["preApprovalFinalDate"] = $preApproval->getPreApprovalFinalDate(); + } + + if ($preApproval->getPreApprovalDayOfMonth() != null) { + $data["preApprovalDayOfMonth"] = $preApproval->getPreApprovalDayOfMonth(); + } + + if ($preApproval->getPreApprovalDayOfWeek() != null) { + $data["preApprovalDayOfWeek"] = $preApproval->getPreApprovalDayOfWeek(); + } + + if ($preApproval->getPreApprovalDayOfYear() != null) { + $data["preApprovalDayOfYear"] = $preApproval->getPreApprovalDayOfYear(); + }; + + if ($preApproval->getPreApprovalPeriod() != null) { + $data["preApprovalPeriod"] = $preApproval->getPreApprovalPeriod(); + } + + if ($preApproval->getPreApprovalAmountPerPayment() != null) { + $data["preApprovalAmountPerPayment"] = $preApproval->getPreApprovalAmountPerPayment(); + } + + if ($preApproval->getPreApprovalMaxAmountPerPayment() != null) { + $data["preApprovalMaxAmountPerPayment"] = $preApproval->getPreApprovalMaxAmountPerPayment(); + } + + if ($preApproval->getPreApprovalMaxPaymentsPerPeriod() != null) { + $data["preApprovalMaxPaymentsPerPeriod"] = $preApproval->getPreApprovalMaxPaymentsPerPeriod(); + } + + if ($preApproval->getPreApprovalDetails() != null) { + $data["preApprovalDetails"] = $preApproval->getPreApprovalDetails(); + } + + if ($preApproval->getPreApprovalName() != null) { + $data["preApprovalName"] = $preApproval->getPreApprovalName(); + } + + if ($preApproval->getPreApprovalCharge() != null) { + $data["preApprovalCharge"] = $preApproval->getPreApprovalCharge(); + } + + return $data; + } + + /** + * @param $preApproval + * @return array + */ + public static function getCharge($preApproval) + { + $data = array(); + + if ($preApproval->getReference() != null) { + $data["reference"] = $preApproval->getReference(); + }; + + if ($preApproval->getPreApprovalCode() != null) { + $data["preApprovalCode"] = $preApproval->getPreApprovalCode(); + }; + + // items + $items = $preApproval->getItems(); + if (count($items) > 0) { + $i = 0; + + foreach ($items as $key => $value) { + $i++; + if ($items[$key]->getId() != null) { + $data["itemId$i"] = $items[$key]->getId(); + } + if ($items[$key]->getDescription() != null) { + $data["itemDescription$i"] = $items[$key]->getDescription(); + } + if ($items[$key]->getQuantity() != null) { + $data["itemQuantity$i"] = $items[$key]->getQuantity(); + } + if ($items[$key]->getAmount() != null) { + $amount = PagSeguroHelper::decimalFormat($items[$key]->getAmount()); + $data["itemAmount$i"] = $amount; + } + } + } + + return $data; + } + + /** + * @param $str_xml + * @return PagSeguroPreApproval + */ + public static function readPreApproval($str_xml) + { + $parser = new PagSeguroXmlParser($str_xml); + $data = $parser->getResult('preApproval'); + $preApproval = new PagSeguroPreApproval(); + + // + if (isset($data["name"])) { + $preApproval->setName($data["name"]); + } + + // + if (isset($data["lastEventDate"])) { + $preApproval->setLastEventDate($data["lastEventDate"]); + } + + // + if (isset($data["date"])) { + $preApproval->setDate($data["date"]); + } + + // + if (isset($data["code"])) { + $preApproval->setCode($data["code"]); + } + + // + if (isset($data["tracker"])) { + $preApproval->setTracker($data["tracker"]); + } + + // + if (isset($data["reference"])) { + $preApproval->setReference($data["reference"]); + } + + // + if (isset($data["charge"])) { + $preApproval->setCharge($data["charge"]); + } + + // + if (isset($data["status"])) { + $preApproval->setStatus(new PagSeguroPreApprovalStatus($data["status"])); + } + + if (isset($data["sender"])) { + // + $sender = new PagSeguroSender(); + + // + if (isset($data["sender"]["name"])) { + $sender->setName($data["sender"]["name"]); + } + + // + if (isset($data["sender"]["email"])) { + $sender->setEmail($data["sender"]["email"]); + } + + if (isset($data["sender"]["phone"])) { + // + $phone = new PagSeguroPhone(); + + // + if (isset($data["sender"]["phone"]["areaCode"])) { + $phone->setAreaCode($data["sender"]["phone"]["areaCode"]); + } + + // + if (isset($data["sender"]["phone"]["number"])) { + $phone->setNumber($data["sender"]["phone"]["number"]); + } + + $sender->setPhone($phone); + } + + // + if (isset($data["sender"]['documents']) && is_array($data["sender"]['documents'])) { + $documents = $data["sender"]['documents']; + if (count($documents) > 0) { + foreach ($documents as $document) { + $sender->addDocument($document['type'], $document['value']); + } + } + } + + $preApproval->setSender($sender); + } + + return $preApproval; + } + + /** + * @param $str_xml + * @return PagSeguroPreApprovalSearchResult + */ + public static function readSearchResult($str_xml) + { + + $parser = new PagSeguroXmlParser($str_xml); + $data = $parser->getResult('preApprovalSearchResult'); + + $result = new PagSeguroPreApprovalSearchResult(); + + if (isset($data['totalPages'])) { + $result->setTotalPages($data['totalPages']); + } + + if (isset($data['date'])) { + $result->setDate($data['date']); + } + + if (isset($data['resultsInThisPage'])) { + $result->setResultsInThisPage($data['resultsInThisPage']); + } + + if (isset($data['currentPage'])) { + $result->setCurrentPage($data['currentPage']); + } + + if (isset($data['preApprovals']) && is_array($data['preApprovals'])) { + $preApprovals = array(); + if (isset($data["preApprovals"]['preApproval'][0])) { + $i = 0; + foreach ($data["preApprovals"]['preApproval'] as $key => $value) { + $preApprovals[$i++] = new PagSeguroPreApproval($value); + } + } else { + $preApprovals[0] = $data["preApprovals"]['preApproval']; + } + $result->setPreApprovals($preApprovals); + } + + return $result; + } + + /** + * @param $str_xml + * @return PagSeguroParserData + */ + public static function readTransactionXml($str_xml) + { + $parser = new PagSeguroXmlParser($str_xml); + $data = $parser->getResult('result'); + $preApprovalParser = new PagSeguroParserData(); + $preApprovalParser->setCode($data['transactionCode']); + $preApprovalParser->setRegistrationDate($data['date']); + return $preApprovalParser; + } + + /** + * @param $str_xml + * @return PagSeguroParserData + */ + public static function readSuccessXml($str_xml) + { + $parser = new PagSeguroXmlParser($str_xml); + $data = $parser->getResult('preApprovalRequest'); + $preApprovalParser = new PagSeguroParserData(); + $preApprovalParser->setCode($data['code']); + $preApprovalParser->setRegistrationDate($data['date']); + return $preApprovalParser; + } + + /** + * @param $str_xml + * @return PagSeguroParserData + */ + public static function readCancelXml($str_xml) + { + $parser = new PagSeguroXmlParser($str_xml); + $data = $parser->getResult('result'); + $preApprovalParser = new PagSeguroParserData(); + $preApprovalParser->setCode(null); // PreApproval API does not send code on cancel requests + $preApprovalParser->setRegistrationDate($data['date']); + $preApprovalParser->setStatus($data['status']); + return $preApprovalParser; + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroRefundParser.class.php b/PagSeguroLibrary/parser/PagSeguroRefundParser.class.php new file mode 100644 index 0000000..7b598a9 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroRefundParser.class.php @@ -0,0 +1,40 @@ +getResult('result'); + + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroServiceParser.class.php b/PagSeguroLibrary/parser/PagSeguroServiceParser.class.php new file mode 100644 index 0000000..3cf8d6a --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroServiceParser.class.php @@ -0,0 +1,52 @@ +getResult('errors'); + $errors = array(); + if (isset($data['error']) && is_array($data['error'])) { + if (isset($data['error']['code']) && isset($data['error']['message'])) { + array_push($errors, new PagSeguroError($data['error']['code'], $data['error']['message'])); + } else { + foreach ($data['error'] as $key => $value) { + if (isset($value['code']) && isset($value['message'])) { + array_push($errors, new PagSeguroError($value['code'], $value['message'])); + } + } + } + } + return $errors; + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroSessionParser.class.php b/PagSeguroLibrary/parser/PagSeguroSessionParser.class.php new file mode 100644 index 0000000..fbeac41 --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroSessionParser.class.php @@ -0,0 +1,48 @@ +getResult('session'); + + $session = new PagSeguroSession(); + + if (isset($data['id'])) { + $session->setId($data['id']); + } + + return $session; + } +} diff --git a/PagSeguroLibrary/parser/PagSeguroTransactionParser.class.php b/PagSeguroLibrary/parser/PagSeguroTransactionParser.class.php new file mode 100644 index 0000000..2b8c5ef --- /dev/null +++ b/PagSeguroLibrary/parser/PagSeguroTransactionParser.class.php @@ -0,0 +1,449 @@ +getResult('transactionSearchResult'); + + $searchResutlt = new PagSeguroTransactionSearchResult(); + + if (isset($data['totalPages'])) { + $searchResutlt->setTotalPages($data['totalPages']); + } + + if (isset($data['date'])) { + $searchResutlt->setDate($data['date']); + } + + if (isset($data['resultsInThisPage'])) { + $searchResutlt->setResultsInThisPage($data['resultsInThisPage']); + } + + if (isset($data['currentPage'])) { + $searchResutlt->setCurrentPage($data['currentPage']); + } + + if (isset($data['transactions']) && is_array($data['transactions'])) { + $transactions = array(); + if (isset($data["transactions"]['transaction'][0])) { + $i = 0; + foreach ($data["transactions"]['transaction'] as $key => $value) { + $transactions[$i++] = self::parseTransactionSummary($value); + } + } else { + $transactions[0] = self::parseTransactionSummary($data["transactions"]['transaction']); + } + $searchResutlt->setTransactions($transactions); + } + + return $searchResutlt; + } + + /*** + * @param $str_xml + * @return PagSeguroTransaction + */ + public static function readTransaction($str_xml) + { + + // Parser + $parser = new PagSeguroXmlParser($str_xml); + + // + $data = $parser->getResult('transaction'); + + $transaction = new PagSeguroTransaction(); + + // + if (isset($data["lastEventDate"])) { + $transaction->setLastEventDate($data["lastEventDate"]); + } + + // + if (isset($data["date"])) { + $transaction->setDate($data["date"]); + } + + // + if (isset($data["code"])) { + $transaction->setCode($data["code"]); + } + + // + if (isset($data["reference"])) { + $transaction->setReference($data["reference"]); + } + + // + if (isset($data["recoveryCode"])) { + $transaction->setRecoveryCode($data["recoveryCode"]); + } + + // + if (isset($data["type"])) { + $transaction->setType(new PagSeguroTransactionType($data["type"])); + } + + // + if (isset($data["status"])) { + $transaction->setStatus(new PagSeguroTransactionStatus($data["status"])); + } + + // + if (isset($data["cancellationSource"])) { + $transaction->setCancellationSource( + new PagSeguroTransactionCancellationSource($data["cancellationSource"]) + ); + } + + if (isset($data["paymentMethod"]) && is_array($data["paymentMethod"])) { + // + $paymentMethod = new PagSeguroPaymentMethod(); + + // + if (isset($data["paymentMethod"]['type'])) { + $paymentMethod->setType(new PagSeguroPaymentMethodType($data["paymentMethod"]['type'])); + } + + // + if (isset($data["paymentMethod"]['code'])) { + $paymentMethod->setCode(new PagSeguroPaymentMethodCode($data["paymentMethod"]['code'])); + } + + $transaction->setPaymentMethod($paymentMethod); + } + + // + if (isset($data["paymentLink"])) { + $transaction->setPaymentLink($data["paymentLink"]); + } + + // + if (isset($data["grossAmount"])) { + $transaction->setGrossAmount($data["grossAmount"]); + } + + // + if (isset($data["discountAmount"])) { + $transaction->setDiscountAmount($data["discountAmount"]); + } + + // + if (isset($data["feeAmount"])) { + $transaction->setFeeAmount($data["feeAmount"]); + } + + // + if (isset($data["netAmount"])) { + $transaction->setNetAmount($data["netAmount"]); + } + + // + if (isset($data["escrowEndDate"])) { + $transaction->setEscrowEndDate($data["escrowEndDate"]); + } + + // + if (isset($data["extraAmount"])) { + $transaction->setExtraAmount($data["extraAmount"]); + } + + // + if (isset($data["installmentCount"])) { + $transaction->setInstallmentCount($data["installmentCount"]); + } + + // + if (isset($data["creditorFees"])) { + $transaction->setCreditorFees(new PagSeguroTransactionCreditorFees($data["creditorFees"])); + } + + // + if (isset($data["operationalFeeAmount"])) { + $transaction->setOperationalFeeAmount($data["operationalFeeAmount"]); + } + + // + if (isset($data["installmentFeeAmount"])) { + $transaction->setInstallmentFeeAmount($data["installmentFeeAmount"]); + } + + // + if (isset($data["intermediationRateAmount"])) { + $transaction->setIntermediationRateAmount($data["intermediationRateAmount"]); + } + + // + if (isset($data["intermediationFeeAmount"])) { + $transaction->setIntermediationFeeAmount($data["intermediationFeeAmount"]); + } + + // + if (isset($data["items"]['item']) && is_array($data["items"]['item'])) { + $items = array(); + $i = 0; + + if (isset($data["items"]['item'][0])) { + foreach ($data["items"]['item'] as $key => $value) { + $item = self::parseTransactionItem($value); + $items[$i] = $item; + $i++; + } + } else { + $items[0] = self::parseTransactionItem($data["items"]['item']); + } + + // + $transaction->setItems($items); + } + + if (isset($data["sender"])) { + // + $sender = new PagSeguroSender(); + + // + if (isset($data["sender"]["name"])) { + $sender->setName($data["sender"]["name"]); + } + + // + if (isset($data["sender"]["email"])) { + $sender->setEmail($data["sender"]["email"]); + } + + if (isset($data["sender"]["phone"])) { + // + $phone = new PagSeguroPhone(); + + // + if (isset($data["sender"]["phone"]["areaCode"])) { + $phone->setAreaCode($data["sender"]["phone"]["areaCode"]); + } + + // + if (isset($data["sender"]["phone"]["number"])) { + $phone->setNumber($data["sender"]["phone"]["number"]); + } + + $sender->setPhone($phone); + } + + // + if (isset($data["sender"]['documents']) && is_array($data["sender"]['documents'])) { + $documents = $data["sender"]['documents']; + if (count($documents) > 0) { + foreach ($documents as $document) { + $sender->addDocument($document['type'], $document['value']); + } + } + } + + $transaction->setSender($sender); + } + + if (isset($data["shipping"]) && is_array($data["shipping"])) { + // + $shipping = new PagSeguroShipping(); + + // + if (isset($data["shipping"]["type"])) { + $shipping->setType(new PagSeguroShippingType($data["shipping"]["type"])); + } + + // + if (isset($data["shipping"]["cost"])) { + $shipping->setCost($data["shipping"]["cost"]); + } + + if (isset($data["shipping"]["address"]) && is_array($data["shipping"]["address"])) { + //
+ $address = new PagSeguroAddress(); + + //
+ if (isset($data["shipping"]["address"]["street"])) { + $address->setStreet($data["shipping"]["address"]["street"]); + } + + //
+ if (isset($data["shipping"]["address"]["number"])) { + $address->setNumber($data["shipping"]["address"]["number"]); + } + + //
+ if (isset($data["shipping"]["address"]["complement"])) { + $address->setComplement($data["shipping"]["address"]["complement"]); + } + + //
+ if (isset($data["shipping"]["address"]["city"])) { + $address->setCity($data["shipping"]["address"]["city"]); + } + + //
+ if (isset($data["shipping"]["address"]["state"])) { + $address->setState($data["shipping"]["address"]["state"]); + } + + //
+ if (isset($data["shipping"]["address"]["district"])) { + $address->setDistrict($data["shipping"]["address"]["district"]); + } + + //
+ if (isset($data["shipping"]["address"]["postalCode"])) { + $address->setPostalCode($data["shipping"]["address"]["postalCode"]); + } + + //
+ if (isset($data["shipping"]["address"]["country"])) { + $address->setCountry($data["shipping"]["address"]["country"]); + } + + $shipping->setAddress($address); + } + + // + $transaction->setShipping($shipping); + } + + return $transaction; + } + + /*** + * @param $data + * @return PagSeguroItem + */ + private static function parseTransactionItem($data) + { + + // + $item = new PagSeguroItem(); + + // + if (isset($data["id"])) { + $item->setId($data["id"]); + } + + // + if (isset($data["description"])) { + $item->setDescription($data["description"]); + } + + // + if (isset($data["quantity"])) { + $item->setQuantity($data["quantity"]); + } + + // + if (isset($data["amount"])) { + $item->setAmount($data["amount"]); + } + + // + if (isset($data["weight"])) { + $item->setWeight($data["weight"]); + } + + return $item; + } + + /*** + * @param $data + * @return PagSeguroTransactionSummary + */ + private static function parseTransactionSummary($data) + { + + $transactionSummary = new PagSeguroTransactionSummary(); + + if (isset($data['type'])) { + $transactionSummary->setType(new PagSeguroTransactionType($data['type'])); + } + if (isset($data['code'])) { + $transactionSummary->setCode($data['code']); + } + if (isset($data['reference'])) { + $transactionSummary->setReference($data['reference']); + } + if (isset($data['date'])) { + $transactionSummary->setDate($data['date']); + } + if (isset($data['lastEventDate'])) { + $transactionSummary->setLastEventDate($data['lastEventDate']); + } + if (isset($data['grossAmount'])) { + $transactionSummary->setGrossAmount($data['grossAmount']); + } + if (isset($data['status'])) { + $transactionSummary->setStatus(new PagSeguroTransactionStatus($data['status'])); + } + if (isset($data["cancellationSource"])) { + $transactionSummary->setCancellationSource( + new PagSeguroTransactionCancellationSource($data["cancellationSource"]) + ); + } + if (isset($data['netAmount'])) { + $transactionSummary->setNetAmount($data['netAmount']); + } + if (isset($data['discountAmount'])) { + $transactionSummary->setDiscountAmount($data['discountAmount']); + } + if (isset($data['feeAmount'])) { + $transactionSummary->setFeeAmount($data['feeAmount']); + } + if (isset($data['extraAmount'])) { + $transactionSummary->setExtraAmount($data['extraAmount']); + } + if (isset($data['lastEvent'])) { + $transactionSummary->setLastEventDate($data['lastEvent']); + } + if (isset($data['paymentMethod'])) { + $paymentMethod = new PagSeguroPaymentMethod(); + if (isset($data['paymentMethod']['type'])) { + $paymentMethod->setType(new PagSeguroPaymentMethodType($data['paymentMethod']['type'])); + } + if (isset($data['paymentMethod']['code'])) { + $paymentMethod->setCode(new PagSeguroPaymentMethodCode($data['paymentMethod']['code'])); + } + $transactionSummary->setPaymentMethod($paymentMethod); + } + + if (isset($data["recoveryCode"])) { + $transactionSummary->setRecoveryCode($data["recoveryCode"]); + } + + return $transactionSummary; + } +} diff --git a/PagSeguroLibrary/resources/PagSeguroResources.class.php b/PagSeguroLibrary/resources/PagSeguroResources.class.php new file mode 100644 index 0000000..c0bbf2b --- /dev/null +++ b/PagSeguroLibrary/resources/PagSeguroResources.class.php @@ -0,0 +1,214 @@ +getServiceUrl(); + return "{$url}/{$authorizationCode}/?" . $connectionData->getCredentialsUrlQuery(); + } + /** + * @param PagSeguroConnectionData $connectionData + * @param $notificationCode + * @return string + */ + private static function buildSearchUrlByNotification(PagSeguroConnectionData $connectionData, $notificationCode) + { + $url = $connectionData->getServiceUrl(); + return "{$url}/notifications/{$notificationCode}/?" . $connectionData->getCredentialsUrlQuery(); + } + /** + * @param PagSeguroConnectionData $connectionData + * @param null|array $options + * @return string + */ + private static function buildSearchUrl(PagSeguroConnectionData $connectionData, $options = null) + { + if (!is_null($options)) { + $options = http_build_query($options, '', '&'); + return $connectionData->getServiceUrl() . "/?" . $connectionData->getCredentialsUrlQuery() . "&" . $options; + } + return $connectionData->getServiceUrl() . "/?" . $connectionData->getCredentialsUrlQuery(); + } + + /** + * @param PagSeguroConnectionData $connectionData + * @param $reference + * @return string + */ + private static function buildSearchUrlByReference(PagSeguroConnectionData $connectionData, $reference) + { + $url = $connectionData->getServiceUrl(); + return "{$url}?" . $connectionData->getCredentialsUrlQuery() . '&reference='.$reference; + } + + /*** + * Finds a authorization with a matching authorization code + * + * @param PagSeguroCredentials $credentials + * @param String $authorizationCode + * @return PagSeguroAuthorization a authorization object + * @see PagSeguroAuthorization + * @throws PagSeguroServiceException + * @throws Exception + */ + public static function searchByCode(PagSeguroCredentials $credentials, $authorizationCode) + { + LogPagSeguro::info("PagSeguroAuthorizationSearchService.SearchByCode($authorizationCode) - begin"); + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrlByCode($connectionData, $authorizationCode), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$logService = "SearchByCode"; + return self::searchReturn($connection, $authorizationCode); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + /*** + * Finds a authorization with a matching notification code + * + * @param PagSeguroCredentials $credentials + * @param String $notificationCode + * @return PagSeguroAuthorization a authorization object + * @see PagSeguroAuthorization + * @throws PagSeguroServiceException + * @throws Exception + */ + public static function searchByNotificationCode(PagSeguroCredentials $credentials, $notificationCode) + { + LogPagSeguro::info("PagSeguroAuthorizationSearchService.searchByNotificationCode($notificationCode) - begin"); + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrlByNotification($connectionData, $notificationCode), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$logService = "SearchByNotificationCode"; + return self::searchReturn($connection, $notificationCode); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + /*** + * Finds a authorization with a matching authorization credentials + * + * @param PagSeguroCredentials $credentials + * @param array $options + * @return PagSeguroAuthorization a authorization object + * @see PagSeguroAuthorization + * @throws PagSeguroServiceException + * @throws Exception + */ + public static function searchAuthorizations(PagSeguroCredentials $credentials, array $options = null) + { + LogPagSeguro::info("PagSeguroAuthorizationSearchService.searchAuthorizations() - begin"); + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrl($connectionData, $options), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + return self::searchAuthorizationsReturn($connection); + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + /*** + * Finds a authorization with a matching authorization code + * + * @param PagSeguroCredentials $credentials + * @param String $authorizationCode + * @return PagSeguroAuthorization a authorization object + * @see PagSeguroAuthorization + * @throws PagSeguroServiceException + * @throws Exception + */ + public static function searchByReference(PagSeguroCredentials $credentials, $reference) + { + LogPagSeguro::info("PagSeguroAuthorizationSearchService.SearchByReference($reference) - begin"); + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrlByReference($connectionData, $reference), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$logService = "SearchByReference"; + return self::searchAuthorizationsReturn($connection, $reference); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + /** + * @param PagSeguroHttpConnection $connection + * @param string $authorizationCode + * @return bool|mixed|string + * @throws PagSeguroServiceException + */ + private static function searchReturn($connection, $code) + { + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + switch ($httpStatus->getType()) { + case 'OK': + $authorization = PagSeguroAuthorizationParser::readAuthorization($connection->getResponse()); + LogPagSeguro::info( + sprintf("PagSeguroAuthorizationSearchService.%s(code=$code) - end ", self::$logService) . + $authorization->toString() + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroAuthorizationParser::readErrors($connection->getResponse()); + $err = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + sprintf("PagSeguroAuthorizationSearchService.%s(code=$code) - error ", self::$logService) . + $err->getOneLineMessage() + ); + throw $err; + break; + default: + $err = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + sprintf("PagSeguroAuthorizationSearchService.%s(code=$code) - error ", self::$logService) . + $err->getOneLineMessage() + ); + throw $err; + break; + } + return isset($authorization) ? $authorization : false; + } + + /** + * @param PagSeguroHttpConnection $connection + * @return bool|mixed|string + * @throws PagSeguroServiceException + */ + private function searchAuthorizationsReturn($connection) + { + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + switch ($httpStatus->getType()) { + case 'OK': + $authorization = PagSeguroAuthorizationParser::readSearchResult($connection->getResponse()); + + LogPagSeguro::info( + "PagSeguroAuthorizationSearchService.searchAuthorizations() - end " . + $authorization->toString() + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroAuthorizationParser::readErrors($connection->getResponse()); + $err = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroAuthorizationSearchService.searchAuthorizations() - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + default: + $err = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroAuthorizationSearchService.searchAuthorizations() - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + } + return isset($authorization) ? $authorization : false; + } +} diff --git a/PagSeguroLibrary/service/PagSeguroAuthorizationService.class.php b/PagSeguroLibrary/service/PagSeguroAuthorizationService.class.php new file mode 100644 index 0000000..fccb20d --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroAuthorizationService.class.php @@ -0,0 +1,149 @@ +getServiceUrl() . $connectionData->getResource('requestUrl') . '?' . + $connectionData->getCredentialsUrlQuery(); + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param string $code + * @return string + */ + private static function buildAuthorizationApprovalUrl(PagSeguroConnectionData $connectionData, $code) + { + return $connectionData->getBaseUrl() . $connectionData->getResource('approvalUrl') . '?code=' . $code; + } + + /*** + * @param PagSeguroCredentials $credentials + * @param PagSeguroAuthorizationRequest $authorizationRequest + * @param bool $onlyAuthorizationCode + * @return bool|string + * @throws Exception + */ + public static function createAuthorizationRequest( + PagSeguroCredentials $credentials, + PagSeguroAuthorizationRequest $authorizationRequest, + $onlyAuthorizationCode + ) { + + LogPagSeguro::info("PagSeguroAuthorizationService.Register(" . $authorizationRequest->toString() . ") - begin"); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + self::buildAuthorizationUrl($connectionData), + PagSeguroAuthorizationParser::getData($authorizationRequest), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + return self::authorizationReturn( + $connection, + $authorizationRequest, + $connectionData, + $onlyAuthorizationCode + ); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + /** + * @param PagSeguroHttpConnection $connection + * @param PagSeguroAuthorizationRequest $authorizationRequest + * @param PagSeguroConnectionData $connectionData + * @param null $onlyAuthorizationCode + * @return bool|mixed|string + * @throws PagSeguroServiceException + */ + private static function authorizationReturn( + PagSeguroHttpConnection $connection, + PagSeguroAuthorizationRequest $authorizationRequest, + PagSeguroConnectionData $connectionData, + $onlyAuthorizationCode = null + ) { + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + $authorization = PagSeguroAuthorizationParser::readSuccessXml($connection->getResponse()); + + if ($onlyAuthorizationCode) { + $authorizationReturn = $authorization->getCode(); + } else { + $authorizationReturn = self::buildAuthorizationApprovalUrl( + $connectionData, + $authorization->getCode() + ); + } + LogPagSeguro::info( + "PagSeguroAuthorizationService.Register(" . $authorizationRequest->toString() . ") - end {1}" . + $authorization->getCode() + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroPaymentParser::readErrors($connection->getResponse()); + $err = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroAuthorizationService.Register(" . $authorizationRequest->toString() . ") - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + default: + $err = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroAuthorizationService.Register(" . $authorizationRequest->toString() . ") - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + } + return (isset($authorizationReturn) ? $authorizationReturn : false); + } +} diff --git a/PagSeguroLibrary/service/PagSeguroCancelService.class.php b/PagSeguroLibrary/service/PagSeguroCancelService.class.php new file mode 100644 index 0000000..58977ae --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroCancelService.class.php @@ -0,0 +1,116 @@ +getServiceUrl() . '?' . $connectionData->getCredentialsUrlQuery() + . "&transactionCode=" . $transactionCode; + } + + /** + * @param PagSeguroCredentials $credentials + * @param $transactionCode + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function requestCancel( + PagSeguroCredentials $credentials, + $transactionCode + ) { + + LogPagSeguro::info("PagSeguroCancelService.Register(".$transactionCode.") - begin"); + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + self::buildCancelURL($connectionData, $transactionCode), + array(), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + return self::getResult($connection); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + /** + * @param $connection + * @return null|PagSeguroParserData + * @throws PagSeguroServiceException + */ + private function getResult($connection) + { + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + + $cancel = PagSeguroCancelParser::readSuccessXml($connection->getResponse()); + LogPagSeguro::info( + "PagSeguroCancelService.createRequest(".$cancel.") - end " + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroCancelParser::readErrors($connection->getResponse()); + $err = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroCancelService.createRequest() - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + default: + $err = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroCancelService.createRequest() - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + } + return isset($cancel) ? $cancel : false; + } +} diff --git a/PagSeguroLibrary/service/PagSeguroConnectionData.class.php b/PagSeguroLibrary/service/PagSeguroConnectionData.class.php new file mode 100644 index 0000000..c39f6b0 --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroConnectionData.class.php @@ -0,0 +1,321 @@ +credentials = $credentials; + $this->serviceName = $serviceName; + + try { + $this->setEnvironment(PagSeguroConfig::getEnvironment()); + $this->setWebserviceUrl(PagSeguroResources::getWebserviceUrl($this->getEnvironment())); + $this->setPaymentUrl(PagSeguroResources::getPaymentUrl($this->getEnvironment())); + $this->setBaseUrl(PagSeguroResources::getBaseUrl($this->getEnvironment())); + $this->setInstallmentUrl(PagSeguroResources::getInstallmentUrl()); + $this->setAuthorizationUrl(PagSeguroResources::getAuthorizationUrl()); + $this->setSessionUrl(PagSeguroResources::getSessionUrl()); + $this->setCharset(PagSeguroConfig::getApplicationCharset()); + + $this->resources = PagSeguroResources::getData($this->serviceName); + if (isset($this->resources['servicePath'])) { + $this->setServicePath($this->resources['servicePath']); + } + if (isset($this->resources['serviceTimeout'])) { + $this->setServiceTimeout($this->resources['serviceTimeout']); + } + } catch (Exception $e) { + throw $e; + } + } + + /*** + * @return PagSeguroCredentials + */ + public function getCredentials() + { + return $this->credentials; + } + + /*** + * @param PagSeguroCredentials $credentials + */ + public function setCredentials(PagSeguroCredentials $credentials) + { + $this->credentials = $credentials; + } + + /*** + * @return string + */ + public function getCredentialsUrlQuery() + { + return http_build_query($this->credentials->getAttributesMap(), '', '&'); + } + + /*** + * @return mixed + */ + public function getEnvironment() + { + return $this->environment; + } + + /*** + * @param $environment + */ + public function setEnvironment($environment) + { + $this->environment = $environment; + } + + /*** + * @return mixed + */ + public function getWebserviceUrl() + { + return $this->webserviceUrl; + } + + /*** + * @param $webserviceUrl + */ + public function setWebserviceUrl($webserviceUrl) + { + $this->webserviceUrl = $webserviceUrl; + } + + /*** + * @return mixed + */ + public function getPaymentUrl() + { + return $this->paymentUrl; + } + + /*** + * @param $paymentUrl + */ + public function setPaymentUrl($paymentUrl) + { + $this->paymentUrl = $paymentUrl; + } + + /*** + * @return mixed + */ + public function getBaseUrl() + { + return $this->baseUrl; + } + + /*** + * @param $baseUrl + */ + public function setBaseUrl($baseUrl) + { + $this->baseUrl = $baseUrl; + } + + /*** + * @return mixed + */ + public function getInstallmentUrl() + { + return $this->installmentUrl; + } + + /*** + * @param $installmentUrl + */ + public function setInstallmentUrl($installmentUrl) + { + $this->installmentUrl = $installmentUrl; + } + + /*** + * @return mixed + */ + public function getAuthorizationUrl() + { + return $this->authorizationUrl; + } + + /*** + * @param $installmentUrl + */ + public function setAuthorizationUrl($authorizationUrl) + { + $this->authorizationUrl = $authorizationUrl; + } + + /*** + * @return mixed + */ + public function getSessionUrl() + { + return $this->sessionUrl; + } + + /*** + * @param $installmentUrl + */ + public function setSessionUrl($sessionUrl) + { + $this->sessionUrl = $sessionUrl; + } + + /*** + * @param mixed $version + * @return mixed + */ + public function getServicePath($version = null) + { + if ($version) { + return $this->servicePath[$version]; + } else { + return $this->servicePath; + } + } + + /*** + * @param $servicePath + */ + public function setServicePath($servicePath) + { + $this->servicePath = $servicePath; + } + + /*** + * @return mixed + */ + public function getServiceTimeout() + { + return $this->serviceTimeout; + } + + /*** + * @param $serviceTimeout + */ + public function setServiceTimeout($serviceTimeout) + { + $this->serviceTimeout = $serviceTimeout; + } + + /*** + * @param mixed $version + * @return string + */ + public function getServiceUrl($version = null) + { + if ($version) { + return $this->getWebserviceUrl() . $this->getServicePath($version); + } else { + return $this->getWebserviceUrl() . $this->getServicePath(); + } + } + + /*** + * @param $resource + * @return mixed + */ + public function getResource($resource) + { + return $this->resources[$resource]; + } + + /*** + * @return mixed + */ + public function getCharset() + { + return $this->charset; + } + + /*** + * @param $charset + */ + public function setCharset($charset) + { + $this->charset = $charset; + } +} diff --git a/PagSeguroLibrary/service/PagSeguroDirectPaymentService.class.php b/PagSeguroLibrary/service/PagSeguroDirectPaymentService.class.php new file mode 100644 index 0000000..88c4f2e --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroDirectPaymentService.class.php @@ -0,0 +1,136 @@ +getServiceUrl() . '/?' . $connectionData->getCredentialsUrlQuery(); + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $code + * @return string + */ + private static function buildReturnUrl(PagSeguroConnectionData $connectionData, $code) + { + return $connectionData->getServiceUrl() . '/' .$code . '/?' . $connectionData->getCredentialsUrlQuery(); + } + + /*** + * checkoutRequest is the actual implementation of the Register method + * This separation serves as test hook to validate the Uri + * against the code returned by the service + * @param PagSeguroCredentials $credentials + * @param PagSeguroDirectrequest $request + * @return bool|string + * @throws Exception|PagSeguroServiceException + * @throws Exception + */ + public static function checkoutRequest( + PagSeguroCredentials $credentials, + PagSeguroDirectPaymentRequest $request + ) { + + LogPagSeguro::info("PagSeguroDirectPaymentService.Register(" . $request->toString() . ") - begin"); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + self::buildCheckoutRequestUrl($connectionData), + PagSeguroDirectPaymentParser::getData($request), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + return self::getResult($connection, $request); + + } catch (PagSeguroServiceException $error) { + throw $error; + } catch (Exception $error) { + LogPagSeguro::error("Exception: " . $error->getMessage()); + throw $error; + } + } + + /** + * @param $connection + * @param PagSeguroDirectPaymentRequest $request + * @return null|PagSeguroParserData + * @throws PagSeguroServiceException + */ + private static function getResult($connection, PagSeguroDirectPaymentRequest $request) + { + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + $paymentReturn = PagSeguroTransactionParser::readTransaction($connection->getResponse()); + + LogPagSeguro::info( + "PagSeguroDirectPaymentService.Register(" . $request->toString() . ") - end {1}" . + $paymentReturn->getCode() + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroTransactionParser::readErrors($connection->getResponse()); + $error = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroDirectPaymentService.Register(" . $request->toString() . ") - error " . + $error->getOneLineMessage() + ); + throw $error; + break; + default: + $error = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroDirectPaymentService.Register(" . $request->toString() . ") - error " . + $error->getOneLineMessage() + ); + throw $error; + break; + } + return (isset($paymentReturn) ? $paymentReturn : false); + } +} diff --git a/PagSeguroLibrary/service/PagSeguroInstallmentService.class.php b/PagSeguroLibrary/service/PagSeguroInstallmentService.class.php new file mode 100644 index 0000000..ccd07bc --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroInstallmentService.class.php @@ -0,0 +1,125 @@ +getBaseUrl() . $connectionData->getInstallmentUrl(); + } + + /*** + * Get from webservice installments for direct payment. + * @param PagSeguroAccountCredentials $credentials + * @param mixed $session ID + * @param float $amount + * @param string $cardBrand + * @return bool|string + * @throws Exception|PagSeguroServiceException + * @throws Exception + */ + public static function getInstallments( + $credentials, + $session, + $amount, + $cardBrand + ) { + + $connectionData = new PagSeguroConnectionData($credentials, 'installmentService'); + + $url = self::buildInstallmentURL($connectionData) . + "?sessionId=" . $session . + "&amount=". $amount . + "&creditCardBrand=" . $cardBrand; + + LogPagSeguro::info( + "PagSeguroInstallmentService.getInstallments(".$amount.",".$cardBrand.") - begin" + ); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + $url, + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + $installments = PagSeguroInstallmentParser::readInstallments($connection->getResponse()); + + if (is_array($installments)) { + LogPagSeguro::info( + "PagSeguroInstallmentService.getInstallments() - end {1}" + ); + + } else { + LogPagSeguro::info( + "PagSeguroInstallmentService.getInstallments() - error" . + $installments->message + ); + + throw new Exception($installments->message); + } + + break; + case 'BAD_REQUEST': + $errors = PagSeguroInstallmentParser::readErrors($connection->getResponse()); + $e = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroInstallmentService.getInstallments() - error " . + $e->getOneLineMessage() + ); + throw $e; + break; + default: + $e = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroInstallmentService.getInstallments() - error " . + $e->getOneLineMessage() + ); + throw $e; + break; + + } + return (isset($installments) ? $installments : false); + + } catch (PagSeguroServiceException $e) { + throw $e; + } catch (Exception $e) { + LogPagSeguro::error("Exception: " . $e->getMessage()); + throw $e; + } + } +} diff --git a/PagSeguroLibrary/service/PagSeguroNotificationService.class.php b/PagSeguroLibrary/service/PagSeguroNotificationService.class.php new file mode 100644 index 0000000..a0f238e --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroNotificationService.class.php @@ -0,0 +1,253 @@ +getServiceUrl(); + return "{$url}/{$notificationCode}/?" . $connectionData->getCredentialsUrlQuery(); + } + + + /** + * @param PagSeguroConnectionData $connectionData + * @param $notificationCode + * @return string + */ + private static function buildAuthorizationNotificationUrl( + PagSeguroConnectionData $connectionData, + $notificationCode + ) { + $url = $connectionData->getWebserviceUrl() . '/' . $connectionData->getResource('applicationPath'); + return "{$url}/{$notificationCode}/?" . $connectionData->getCredentialsUrlQuery(); + } + + + /** + * @param PagSeguroConnectionData $connectionData + * @param $preApprovalCode + * @return string + */ + private static function buildPreApprovalNotificationUrl( + PagSeguroConnectionData $connectionData, + $preApprovalCode + ) { + $url = $connectionData->getWebserviceUrl() . '/' . $connectionData->getResource('preApprovalPath'); + return "{$url}/{$preApprovalCode}/?" . $connectionData->getCredentialsUrlQuery(); + } + + /*** + * Returns a transaction from a notification code + * + * @param PagSeguroCredentials $credentials + * @param String $notificationCode + * @throws PagSeguroServiceException + * @throws Exception + * @return PagSeguroTransaction + * @see PagSeguroTransaction + */ + public static function checkTransaction(PagSeguroCredentials $credentials, $notificationCode) + { + + LogPagSeguro::info( + "PagSeguroNotificationService.CheckTransaction(notificationCode=$notificationCode) - begin" + ); + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildTransactionNotificationUrl($connectionData, $notificationCode), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$service = "CheckTransaction"; + return self::getResult($connection, $notificationCode); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + /** + * Returns a authorization from a notification code + * @param PagSeguroCredentials $credentials + * @param $notificationCode + * @return bool|mixed|string + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function checkAuthorization(PagSeguroCredentials $credentials, $notificationCode) + { + + LogPagSeguro::info( + "PagSeguroNotificationService.CheckAuthorization(notificationCode=$notificationCode) - begin" + ); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildAuthorizationNotificationUrl($connectionData, $notificationCode), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$service = "CheckAuthorization"; + return self::getResult($connection, $notificationCode); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + /** + * Returns a pre approval from a notification code + * @param PagSeguroCredentials $credentials + * @param $notificationCode + * @return bool|mixed|string + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function checkPreApproval(PagSeguroCredentials $credentials, $notificationCode) + { + + LogPagSeguro::info( + "PagSeguroNotificationService.CheckPreApproval(notificationCode=$notificationCode) - begin" + ); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildPreApprovalNotificationUrl($connectionData, $notificationCode), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$service = "CheckPreApproval"; + return self::getResult($connection, $notificationCode); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } + + + /** + * @param PagSeguroConnectionData $connection + * @param $code + * @return null|PagSeguroAuthorization|PagSeguroParserData|PagSeguroTransaction + * @throws PagSeguroServiceException + */ + private static function getResult($connection, $code) + { + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + $response = $connection->getResponse(); + + switch ($httpStatus->getType()) { + case 'OK': + switch(self::$service) { + case "CheckPreApproval": + $response = PagSeguroPreApprovalParser::readPreApproval($response); + break; + case "CheckAuthorization": + $response = PagSeguroAuthorizationParser::readAuthorization($response); + break; + case "CheckTransaction": + $response = PagSeguroTransactionParser::readTransaction($response); + break; + } + //Logging + $log['text'] = sprintf( + "PagSeguroNotificationService.%s(notificationCode=$code) - end ", + self::$service + ); + $log['action'] = $response->toString(); + LogPagSeguro::info($log['text'] .$log['action'] . ")"); + + break; + case 'BAD_REQUEST': + + $errors = PagSeguroServiceParser::readErrors($connection->getResponse()); + $errors = new PagSeguroServiceException($httpStatus, $errors); + //Logging + $log['text'] = sprintf( + "PagSeguroNotificationService.%s(notificationCode=$code) - error ", + self::$service + ); + LogPagSeguro::error($log['text'] . $errors->getOneLineMessage()); + //Exception + throw $errors; + + break; + default: + $errors = new PagSeguroServiceException($httpStatus); + //Logging + $log['text'] = sprintf( + "PagSeguroNotificationService.%s(notificationCode=$code) - error ", + self::$service + ); + LogPagSeguro::info($log['text'].$errors->getOneLineMessage()); + //Exception + throw $errors; + break; + } + return isset($response) ? $response : null; + } +} diff --git a/PagSeguroLibrary/service/PagSeguroPaymentService.class.php b/PagSeguroLibrary/service/PagSeguroPaymentService.class.php new file mode 100644 index 0000000..1f4d400 --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroPaymentService.class.php @@ -0,0 +1,127 @@ +getServiceUrl() . '/?' . $connectionData->getCredentialsUrlQuery(); + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $code + * @return string + */ + private static function buildCheckoutUrl(PagSeguroConnectionData $connectionData, $code) + { + return $connectionData->getPaymentUrl() . $connectionData->getResource('checkoutUrl') . "?code=$code"; + } + + /*** + * checkoutRequest is the actual implementation of the Register method + * This separation serves as test hook to validate the Uri + * against the code returned by the service + * @param PagSeguroCredentials $credentials + * @param PagSeguroPaymentRequest $paymentRequest + * @return bool|string + * @throws Exception|PagSeguroServiceException + * @throws Exception + */ + public static function checkoutRequest( + PagSeguroCredentials $credentials, + PagSeguroPaymentRequest $paymentRequest, + $onlyCheckoutCode + ) { + + LogPagSeguro::info("PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - begin"); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + self::buildCheckoutRequestUrl($connectionData), + PagSeguroPaymentParser::getData($paymentRequest), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + $PaymentParserData = PagSeguroPaymentParser::readSuccessXml($connection->getResponse()); + + if ($onlyCheckoutCode) { + $paymentReturn = $PaymentParserData->getCode(); + } else { + $paymentReturn = self::buildCheckoutUrl($connectionData, $PaymentParserData->getCode()); + } + LogPagSeguro::info( + "PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - end {1}" . + $PaymentParserData->getCode() + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroPaymentParser::readErrors($connection->getResponse()); + $error = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - error " . + $error->getOneLineMessage() + ); + throw $error; + break; + default: + $error = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroPaymentService.Register(" . $paymentRequest->toString() . ") - error " . + $error->getOneLineMessage() + ); + throw $error; + break; + + } + return (isset($paymentReturn) ? $paymentReturn : false); + + } catch (PagSeguroServiceException $error) { + throw $error; + } catch (Exception $error) { + LogPagSeguro::error("Exception: " . $error->getMessage()); + throw $error; + } + } +} diff --git a/PagSeguroLibrary/service/PagSeguroPreApprovalSearchService.class.php b/PagSeguroLibrary/service/PagSeguroPreApprovalSearchService.class.php new file mode 100644 index 0000000..9559638 --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroPreApprovalSearchService.class.php @@ -0,0 +1,432 @@ + + * @copyright 2007-2014 PagSeguro Internet Ltda. + * @license http://www.apache.org/licenses/LICENSE-2.0 + */ + +/*** + * Encapsulates web service calls regarding PagSeguro payment requests + */ +class PagSeguroPreApprovalSearchService +{ + + /*** + * + */ + const SERVICE_NAME = 'preApproval'; + /** + * @var + */ + private static $service; + /** + * @var + */ + private static $connectionData; + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $notificationCode + * @return string + */ + private static function buildFindByNotificationUrl(PagSeguroConnectionData $connectionData, $notificationCode) + { + $url = $connectionData->getWebserviceUrl() . $connectionData->getResource('findUrl') . 'notification'; + return "{$url}/{$notificationCode}/?" . $connectionData->getCredentialsUrlQuery(); + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $code + * @return string + */ + private static function buildFindByCodeUrl(PagSeguroConnectionData $connectionData, $code) + { + $url = $connectionData->getWebserviceUrl() . $connectionData->getResource('findUrl'); + return "{$url}{$code}/?" . $connectionData->getCredentialsUrlQuery(); + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $code + * @return string + */ + private static function buildFindByDayIntervalUrl(PagSeguroConnectionData $connectionData, $interval) + { + $url = $connectionData->getWebserviceUrl() . $connectionData->getResource('findUrl') . 'notifications'; + return "{$url}?" . $connectionData->getCredentialsUrlQuery() . "&interval=" . $interval; + } + + /** + * @param PagSeguroConnectionData $connectionData + * @param array $params + * @return string + */ + private static function buildFindByDateIntervalUrl(PagSeguroConnectionData $connectionData, array $params) + { + $url = $connectionData->getWebserviceUrl() . $connectionData->getResource('findUrl'); + $initialDate = $params['initialDate'] != null ? $params['initialDate'] : ""; + $finalDate = $params['finalDate'] != null ? ("&finalDate=" . $params['finalDate']) : ""; + + if ($params['pageNumber'] != null) { + $page = "&page=" . $params['pageNumber']; + } + if ($params['maxPageResults'] != null) { + $maxPageResults = "&maxPageResults=" . $params['maxPageResults']; + } + + return "{$url}?" . $connectionData->getCredentialsUrlQuery() . "&initialDate={$initialDate}{$finalDate} + {$page}{$maxPageResults}"; + } + + /** + * @param PagSeguroConnectionData $connectionData + * @param array $params + * @return string + */ + private static function buildFindByReferenceUrl(PagSeguroConnectionData $connectionData, array $params) + { + $url = $connectionData->getWebserviceUrl() . $connectionData->getResource('findUrl'); + $initialDate = $params['initialDate'] != null ? $params['initialDate'] : ""; + $finalDate = $params['finalDate'] != null ? ("&finalDate=" . $params['finalDate']) : ""; + + $reference = $params['reference'] != null ? ("&reference=" . $params['reference']) : ""; + + if ($params['pageNumber'] != null) { + $page = "&page=" . $params['pageNumber']; + } + if ($params['maxPageResults'] != null) { + $maxPageResults = "&maxPageResults=" . $params['maxPageResults']; + } + + return "{$url}?" . $connectionData->getCredentialsUrlQuery() + . "&initialDate={$initialDate}{$finalDate}{$page}{$maxPageResults}{$reference}"; + } + + /** + * @param $pageNumber + * @param $maxPageResults + * @param $initialDate + * @param null $finalDate + * @return array + */ + private function buildParams($pageNumber, $maxPageResults, $initialDate, $finalDate = null, $reference = null) + { + $params = array( + 'initialDate' => PagSeguroHelper::formatDate($initialDate), + 'pageNumber' => $pageNumber, + 'maxPageResults' => $maxPageResults + ); + + $params['finalDate'] = $finalDate ? PagSeguroHelper::formatDate($finalDate) : null; + + $params['reference'] = $reference ? PagSeguroHelper::formatDate($reference) : null; + + return $params; + } + + /** + * @param PagSeguroCredentials $credentials + * @param $code + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function searchByCode(PagSeguroCredentials $credentials, $code) + { + + LogPagSeguro::info("PagSeguroPreApprovalService.FindByCode($code) - begin"); + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildFindByCodeUrl(self::$connectionData, $code), + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + self::$service = "FindByCode"; + return self::getResult($connection, $code); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + } + + /** + * @param PagSeguroCredentials $credentials + * @param $interval + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function searchByInterval(PagSeguroCredentials $credentials, $interval) + { + + LogPagSeguro::info("PagSeguroPreApprovalService.FindByDayInterval($interval) - begin"); + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildFindByDayIntervalUrl(self::$connectionData, $interval), + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + self::$service = "FindByDayInterval"; + return self::getResult($connection); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + } + + /** + * @param PagSeguroCredentials $credentials + * @param $pageNumber + * @param $maxPageResults + * @param $initialDate + * @param null $finalDate + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function searchByDate( + PagSeguroCredentials $credentials, + $pageNumber, + $maxPageResults, + $initialDate, + $finalDate = null + ) { + //Logging + $log['text'] = "PagSeguroPreApprovalService.FindByDateInterval(initialDate=" + . PagSeguroHelper::formatDate($initialDate) . ", finalDate=" . PagSeguroHelper::formatDate($finalDate) . + "begin"; + LogPagSeguro::info($log['text']); + + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + $params = self::buildParams($pageNumber, $maxPageResults, $initialDate, $finalDate); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildFindByDateIntervalUrl(self::$connectionData, $params), + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + self::$service = "FindByDateInterval"; + return self::getResult($connection); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + } + + /** + * @param PagSeguroCredentials $credentials + * @param $pageNumber + * @param $maxPageResults + * @param $initialDate + * @param null $finalDate + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function searchByReference( + PagSeguroCredentials $credentials, + $pageNumber, + $maxPageResults, + $initialDate, + $finalDate = null, + $reference + ) { + //Logging + $log['text'] = "PagSeguroPreApprovalService.FindByReference(initialDate=" + . PagSeguroHelper::formatDate($initialDate) . ", finalDate=" . PagSeguroHelper::formatDate($finalDate) + . ", reference=" . $reference . "begin"; + LogPagSeguro::info($log['text']); + + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + $params = self::buildParams($pageNumber, $maxPageResults, $initialDate, $finalDate, $reference); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildFindByReferenceUrl(self::$connectionData, $params), + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + + self::$service = "FindByReference"; + return self::getResult($connection); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + } + + /** + * @param PagSeguroCredentials $credentials + * @param $notificationCode + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function findByNotification(PagSeguroCredentials $credentials, $notificationCode) + { + + LogPagSeguro::info("PagSeguroPreApprovalService.FindByNotification($notificationCode) - begin"); + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildFindByNotificationUrl(self::$connectionData, $notificationCode), + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + self::$service = "FindByNotification"; + return self::getResult($connection, $notificationCode); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + } + + /** + * @param $connection + * @param null $code + * @return null|PagSeguroParserData + * @throws PagSeguroServiceException + */ + private function getResult($connection, $code = null) + { + + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + $response = $connection->getResponse(); + + switch ($httpStatus->getType()) { + case 'OK': + switch(self::$service) { + case "FindByCode": + $result = PagSeguroPreApprovalParser::readPreApproval($response); + break; + case "FindByNotification": + $result = PagSeguroPreApprovalParser::readPreApproval($response); + break; + case "FindByDayInterval": + $result = PagSeguroPreApprovalParser::readSearchResult($response); + break; + case "FindByDateInterval": + $result = PagSeguroPreApprovalParser::readSearchResult($response); + break; + case "FindByReference": + $result = PagSeguroPreApprovalParser::readSearchResult($response); + break; + } + + //Logging + if (is_null($code) && self::$service == "PreApprovalRequest") { + $log['text'] = sprintf( + "PagSeguroPreApprovalService.%s(".$response->toString().") - end ", + self::$service + ); + LogPagSeguro::info($log['text'] . ")"); + } else { + $log['text'] = sprintf("PagSeguroPreApprovalService.%s($code) - end ", self::$service); + LogPagSeguro::info($log['text']); + } + + break; + case 'BAD_REQUEST': + + $errors = PagSeguroServiceParser::readErrors($response); + $errors = new PagSeguroServiceException($httpStatus, $errors); + + //Logging + $log['text'] = sprintf("PagSeguroPreApprovalService.%s($code) - error ", self::$service); + LogPagSeguro::error($log['text'] . $errors->getOneLineMessage()); + + //Exception + throw $errors; + + break; + default: + + $errors = new PagSeguroServiceException($httpStatus); + + //Logging + $log['text'] = sprintf("PagSeguroPreApprovalService.%s($code) - error ", self::$service); + LogPagSeguro::error($log['text'] . $errors->getOneLineMessage()); + + //Exception + throw $errors; + + break; + } + return isset($result) ? $result : null; + } +} diff --git a/PagSeguroLibrary/service/PagSeguroPreApprovalService.class.php b/PagSeguroLibrary/service/PagSeguroPreApprovalService.class.php new file mode 100644 index 0000000..0c5c788 --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroPreApprovalService.class.php @@ -0,0 +1,304 @@ + + * @copyright 2007-2014 PagSeguro Internet Ltda. + * @license http://www.apache.org/licenses/LICENSE-2.0 + */ + +/*** + * Encapsulates web service calls regarding PagSeguro payment requests + */ +class PagSeguroPreApprovalService +{ + + /*** + * + */ + const SERVICE_NAME = 'preApproval'; + /** + * @var + */ + private static $service; + /** + * @var + */ + private static $connectionData; + + /*** + * @param PagSeguroConnectionData $connectionData + * @return string + */ + private static function buildPreApprovalUrl(PagSeguroConnectionData $connectionData) + { + return $connectionData->getServiceUrl(); + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $code + * @return string + */ + private static function buildPreApprovalRequestUrl(PagSeguroConnectionData $connectionData, $code) + { + return $connectionData->getPaymentUrl() . $connectionData->getResource('requestUrl') . "?code=$code"; + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $code + * @return string + */ + private static function buildPreApprovalPaymentUrl(PagSeguroConnectionData $connectionData) + { + return $connectionData->getWebserviceUrl() . $connectionData->getResource('paymentUrl'); + } + + /*** + * @param PagSeguroConnectionData $connectionData + * @param $code + * @return string + */ + private static function buildPreApprovalCancelUrl(PagSeguroConnectionData $connectionData, $code) + { + $credentialsArray = $connectionData->getCredentials()->getAttributesMap(); + return $connectionData->getWebserviceUrl() . $connectionData->getResource('cancelUrl') . + "$code?".$connectionData->getCredentialsUrlQuery(); + } + + /** + * @param PagSeguroCredentials $credentials + * @param PagSeguroPaymentRequest $request + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function createPreApprovalRequest( + PagSeguroCredentials $credentials, + PagSeguroPreApprovalRequest $request + ) { + + LogPagSeguro::info( + "PagSeguroPreApprovalService.PreApprovalRequest(" . + $request->toString() . ") - begin" + ); + + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + $data = array_merge( + self::$connectionData->getCredentials()->getAttributesMap(), + PagSeguroPreApprovalParser::getData($request) + ); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + self::buildPreApprovalUrl(self::$connectionData), + $data, + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + + self::$service = "PreApprovalRequest"; + return self::getResult($connection); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + + } + + /** + * @param PagSeguroCredentials $credentials + * @param PagSeguroPreApprovalCharge $charge + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function paymentCharge( + PagSeguroCredentials $credentials, + PagSeguroPreApprovalCharge $charge + ) { + + LogPagSeguro::info( + "PagSeguroPreApprovalService.PreApprovalPaymentCharge(" . + $charge->toString() . ") - begin" + ); + + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + $data = array_merge( + self::$connectionData->getCredentials()->getAttributesMap(), + PagSeguroPreApprovalParser::getCharge($charge) + ); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + self::buildPreApprovalPaymentUrl(self::$connectionData), + $data, + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + + self::$service = "PreApprovalPaymentCharge"; + return self::getResult($connection); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + } + + /** + * @param PagSeguroCredentials $credentials + * @param $code + * @return null|PagSeguroParserData + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function cancelPreApproval(PagSeguroCredentials $credentials, $code) + { + + //Logging + $log['text'] = "PagSeguroNotificationService.PreApprovalCancel($code) - begin"; + LogPagSeguro::info($log['text']); + + self::$connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildPreApprovalCancelUrl( + self::$connectionData, + $code + ), + self::$connectionData->getServiceTimeout(), + self::$connectionData->getCharset() + ); + + self::$service = "PreApprovalCancel"; + return self::getResult($connection, $code); + + } catch (PagSeguroServiceException $err) { + //Logging + LogPagSeguro::error("PagSeguroServiceException: " . $err->getMessage()); + //Exception + throw $err; + + } catch (Exception $err) { + //Logging + LogPagSeguro::error("Exception: " . $err->getMessage()); + //Exception + throw $err; + } + } + + /** + * @param $connection + * @param null $code + * @return null|PagSeguroParserData + * @throws PagSeguroServiceException + */ + private function getResult($connection, $code = null) + { + + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + $response = $connection->getResponse(); + + switch ($httpStatus->getType()) { + case 'OK': + switch(self::$service) { + case "PreApprovalRequest": + + $response = PagSeguroPreApprovalParser::readSuccessXml($response); + + $result = array ( 'code' => $response->getCode(), + 'cancelUrl' => self::buildPreApprovalCancelUrl( + self::$connectionData, + $response->getCode() + ), + 'checkoutUrl' => self::buildPreApprovalRequestUrl( + self::$connectionData, + $response->getCode() + ) ); + + break; + case "PreApprovalCancel": + $result = PagSeguroPreApprovalParser::readCancelXml($response); + break; + case "PreApprovalPaymentCharge": + $result = PagSeguroPreApprovalParser::readTransactionXml($response); + break; + } + + //Logging + if (is_null($code) && self::$service == "PreApprovalRequest") { + $log['text'] = sprintf( + "PagSeguroPreApprovalService.%s(".$response->toString().") - end ", + self::$service + ); + LogPagSeguro::info($log['text'] . ")"); + } else { + $log['text'] = sprintf("PagSeguroPreApprovalService.%s($code) - end ", self::$service); + LogPagSeguro::info($log['text']); + } + + break; + case 'BAD_REQUEST': + + $errors = PagSeguroServiceParser::readErrors($response); + $errors = new PagSeguroServiceException($httpStatus, $errors); + + //Logging + $log['text'] = sprintf("PagSeguroPreApprovalService.%s($code) - error ", self::$service); + LogPagSeguro::error($log['text'] . $errors->getOneLineMessage()); + + //Exception + throw $errors; + break; + default: + + $errors = new PagSeguroServiceException($httpStatus); + + //Logging + $log['text'] = sprintf("PagSeguroPreApprovalService.%s($code) - error ", self::$service); + LogPagSeguro::error($log['text'] . $errors->getOneLineMessage()); + + //Exception + throw $errors; + break; + } + return isset($result) ? $result : null; + } +} diff --git a/PagSeguroLibrary/service/PagSeguroRefundService.class.php b/PagSeguroLibrary/service/PagSeguroRefundService.class.php new file mode 100644 index 0000000..df62443 --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroRefundService.class.php @@ -0,0 +1,104 @@ +getServiceUrl() . '?' . $connectionData->getCredentialsUrlQuery() + . "&transactionCode=" . $transactionCode; + } else { + return $connectionData->getServiceUrl() . '?' . $connectionData->getCredentialsUrlQuery() + . "&transactionCode=" . $transactionCode . "&refundValue=" . $refundValue; + } + } + + public static function createRefundRequest( + PagSeguroCredentials $credentials, + $transactionCode, + $refundValue = null + ) { + + LogPagSeguro::info("PagSeguroRefundService.Register(".$transactionCode.") - begin"); + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + if (is_null($refundValue)) { + $url = self::buildRefundURL($connectionData, $transactionCode); + } else { + $url = self::buildRefundURL($connectionData, $transactionCode, $refundValue); + } + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + $url, + array(), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + + $result = PagSeguroRefundParser::readSuccessXml($connection->getResponse()); + LogPagSeguro::info( + "PagSeguroRefundService.createRefundRequest(".$result.") - end " + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroRefundParser::readErrors($connection->getResponse()); + $err = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroRefundService.createRefundRequest() - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + default: + $err = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroRefundService.createRefundRequest() - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + } + return isset($result) ? $result : false; + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + } +} diff --git a/PagSeguroLibrary/service/PagSeguroSessionService.class.php b/PagSeguroLibrary/service/PagSeguroSessionService.class.php new file mode 100644 index 0000000..f4f0436 --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroSessionService.class.php @@ -0,0 +1,101 @@ +getWebserviceUrl() . $connectionData->getSessionUrl(); + } + + /*** + * Get session for direct payment from webservice + * @param $credentials PagSeguroAccountCredentials + * @return bool|string + * @throws Exception|PagSeguroServiceException + * @throws Exception + */ + public static function getSession($credentials) + { + $connectionData = new PagSeguroConnectionData($credentials, 'sessionService'); + + $url = self::buildSessionURL($connectionData) . "?" . $connectionData->getCredentialsUrlQuery(); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->post( + $url, + array(), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + + $session = PagSeguroSessionParser::readResult($connection->getResponse()); + + return $session->getId(); + + LogPagSeguro::info( + "PagSeguroSessionService.getSession()(" . $session->toString() . ") - end {1}" + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroSessionParser::readErrors($connection->getStatus()); + $e = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroSessionService.getSession() - error " . + $e->getOneLineMessage() + ); + throw $e; + break; + default: + + $e = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroSessionService.getSession() - error " . + $e->getOneLineMessage() + ); + throw $e; + break; + } + } catch (PagSeguroServiceException $e) { + throw $e; + } catch (Exception $e) { + LogPagSeguro::error("Exception: " . $e->getMessage()); + throw $e; + } + } +} diff --git a/PagSeguroLibrary/service/PagSeguroTransactionSearchService.class.php b/PagSeguroLibrary/service/PagSeguroTransactionSearchService.class.php new file mode 100644 index 0000000..0c37ea2 --- /dev/null +++ b/PagSeguroLibrary/service/PagSeguroTransactionSearchService.class.php @@ -0,0 +1,427 @@ +getServiceUrl('v3'); + return "{$url}/{$transactionCode}/?" . $connectionData->getCredentialsUrlQuery(); + } + + /** + * @param PagSeguroConnectionData $connectionData + * @param array $searchParams + * @return string + */ + private static function buildSearchUrlByDate(PagSeguroConnectionData $connectionData, array $searchParams) + { + $url = $connectionData->getServiceUrl('v2'); + $initialDate = $searchParams['initialDate'] != null ? $searchParams['initialDate'] : ""; + $finalDate = $searchParams['finalDate'] != null ? ("&finalDate=" . $searchParams['finalDate']) : ""; + if ($searchParams['pageNumber'] != null) { + $page = "&page=" . $searchParams['pageNumber']; + } + if ($searchParams['maxPageResults'] != null) { + $maxPageResults = "&maxPageResults=" . $searchParams['maxPageResults']; + } + return "{$url}/?" . $connectionData->getCredentialsUrlQuery() . + "&initialDate={$initialDate}{$finalDate}{$page}{$maxPageResults}"; + } + + /** + * @param PagSeguroConnectionData $connectionData + * @param array $searchParams + * @return string + */ + private static function buildSearchUrlAbandoned(PagSeguroConnectionData $connectionData, array $searchParams) + { + $url = $connectionData->getServiceUrl('v2'); + + $initialDate = $searchParams['initialDate'] != null ? $searchParams['initialDate'] : ""; + $finalDate = $searchParams['finalDate'] != null ? ("&finalDate=" . $searchParams['finalDate']) : ""; + if ($searchParams['pageNumber'] != null) { + $page = "&page=" . $searchParams['pageNumber']; + } + if ($searchParams['maxPageResults'] != null) { + $maxPageResults = "&maxPageResults=" . $searchParams['maxPageResults']; + } + return "{$url}/abandoned/?" . $connectionData->getCredentialsUrlQuery() . + "&initialDate={$initialDate}{$finalDate}{$page}{$maxPageResults}"; + } + + /** + * @param PagSeguroConnectionData $connectionData + * @param $reference + * @param null $searchParams + * @return string + */ + private static function buildSearchUrlByReference( + PagSeguroConnectionData $connectionData, + $reference, + $searchParams = null + ) { + $url = $connectionData->getServiceUrl('v2'); + if ($searchParams == null) { + return "{$url}?" . $connectionData->getCredentialsUrlQuery() . "&reference=" . $reference; + } else { + $initialDate = $searchParams['initialDate'] != null ? $searchParams['initialDate'] : ""; + $finalDate = $searchParams['finalDate'] != null ? ("&finalDate=" . $searchParams['finalDate']) : ""; + if ($searchParams['pageNumber'] != null) { + $page = "&page=" . $searchParams['pageNumber']; + } + if ($searchParams['maxPageResults'] != null) { + $maxPageResults = "&maxPageResults=" . $searchParams['maxPageResults']; + } + + return "{$url}?" . $connectionData->getCredentialsUrlQuery() . "&reference=" . $reference + . "&initialDate={$initialDate}&finalDate={$finalDate}{$page}{$maxPageResults}"; + } + } + + /*** + * Finds a transaction with a matching transaction code + * + * @param PagSeguroCredentials $credentials + * @param String $transactionCode + * @return PagSeguroTransaction a transaction object + * @see PagSeguroTransaction + * @throws PagSeguroServiceException + * @throws Exception + */ + public static function searchByCode(PagSeguroCredentials $credentials, $transactionCode) + { + + LogPagSeguro::info("PagSeguroTransactionSearchService.SearchByCode($transactionCode) - begin"); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrlByCode($connectionData, $transactionCode), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + return self::searchByCodeResult($connection, $transactionCode); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + + } + + /*** + * Search transactions associated with this set of credentials within a date range + * + * @param PagSeguroCredentials $credentials + * @param integer $pageNumber + * @param integer $maxPageResults + * @param String $initialDate + * @param String $finalDate + * @return a object of PagSeguroTransactionSerachResult class + * @see PagSeguroTransactionSearchResult + * @throws PagSeguroServiceException + * @throws Exception + */ + public static function searchByDate( + PagSeguroCredentials $credentials, + $pageNumber, + $maxPageResults, + $initialDate, + $finalDate = null + ) { + + LogPagSeguro::info( + "PagSeguroTransactionSearchService.SearchByDate(initialDate=" . PagSeguroHelper::formatDate($initialDate) . + ", finalDate=" . PagSeguroHelper::formatDate($finalDate) . ") - begin" + ); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + $searchParams = self::buildParams($pageNumber, $maxPageResults, $initialDate, $finalDate); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrlByDate($connectionData, $searchParams), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$logService = "SearchByDate"; + return self::searchResult($connection, $initialDate, $finalDate); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + + } + + /*** + * Search transactions abandoned associated with this set of credentials within a date range + * + * @param PagSeguroCredentials $credentials + * @param String $initialDate + * @param String $finalDate + * @param integer $pageNumber + * @param integer $maxPageResults + * @return PagSeguroTransactionSearchResult a object of PagSeguroTransactionSearchResult class + * @see PagSeguroTransactionSearchResult + * @throws PagSeguroServiceException + * @throws Exception + */ + public static function searchAbandoned( + PagSeguroCredentials $credentials, + $pageNumber, + $maxPageResults, + $initialDate, + $finalDate = null + ) { + + LogPagSeguro::info( + "PagSeguroTransactionSearchService.searchAbandoned(initialDate=" . + PagSeguroHelper::formatDate($initialDate) . ", finalDate=" . + PagSeguroHelper::formatDate($finalDate) . ") - begin" + ); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + $searchParams = self::buildParams($pageNumber, $maxPageResults, $initialDate, $finalDate); + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrlAbandoned($connectionData, $searchParams), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$logService = "searchAbandoned"; + return self::searchResult($connection, $initialDate, $finalDate); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + + } + + /** + * @param PagSeguroCredentials $credentials + * @param $reference + * @param null $initialDate + * @param null $finalDate + * @param null $pageNumber + * @param null $maxPageResults + * @throws Exception + * @throws PagSeguroServiceException + */ + public static function searchByReference( + PagSeguroCredentials $credentials, + $reference, + $initialDate = null, + $finalDate = null, + $pageNumber = null, + $maxPageResults = null + ) { + + LogPagSeguro::info( + "PagSeguroTransactionSearchService.SearchByReference(reference=".$reference.") - begin" + ); + + $connectionData = new PagSeguroConnectionData($credentials, self::SERVICE_NAME); + + if ($initialDate) { + $searchParams = self::buildParams($pageNumber, $maxPageResults, $initialDate, $finalDate); + } else { + $searchParams = null; + } + + try { + $connection = new PagSeguroHttpConnection(); + $connection->get( + self::buildSearchUrlByReference( + $connectionData, + $reference, + $searchParams + ), + $connectionData->getServiceTimeout(), + $connectionData->getCharset() + ); + + self::$logService = "SearchByReference"; + return self::searchResult($connection); + + } catch (PagSeguroServiceException $err) { + throw $err; + } catch (Exception $err) { + LogPagSeguro::error("Exception: " . $err->getMessage()); + throw $err; + } + + } + + /** + * @param $pageNumber + * @param $maxPageResults + * @param $initialDate + * @param null $finalDate + * @return array + */ + private function buildParams($pageNumber, $maxPageResults, $initialDate, $finalDate = null) + { + $searchParams = array( + 'initialDate' => PagSeguroHelper::formatDate($initialDate), + 'pageNumber' => $pageNumber, + 'maxPageResults' => $maxPageResults + ); + + $searchParams['finalDate'] = $finalDate ? PagSeguroHelper::formatDate($finalDate) : null; + + return $searchParams; + } + + /** + * @param $connection + * @param $code + * @return bool|PagSeguroTransaction + * @throws PagSeguroServiceException + */ + private static function searchByCodeResult($connection, $code) + { + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + $transaction = PagSeguroTransactionParser::readTransaction($connection->getResponse()); + LogPagSeguro::info( + "PagSeguroTransactionSearchService.SearchByCode(transactionCode=$code) - end " . + $transaction->toString() + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroTransactionParser::readErrors($connection->getResponse()); + $err = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + "PagSeguroTransactionSearchService.SearchByCode(transactionCode=$code) - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + default: + $err = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + "PagSeguroTransactionSearchService.SearchByCode(transactionCode=$code) - error " . + $err->getOneLineMessage() + ); + throw $err; + break; + } + return isset($transaction) ? $transaction : false; + } + + /** + * @param $connection + * @param null $initialDate + * @param null $finalDate + * @return bool|PagSeguroTransactionSearchResult + * @throws PagSeguroServiceException + */ + private function searchResult($connection, $initialDate = null, $finalDate = null) + { + + $httpStatus = new PagSeguroHttpStatus($connection->getStatus()); + + switch ($httpStatus->getType()) { + case 'OK': + + $searchResult = PagSeguroTransactionParser::readSearchResult($connection->getResponse()); + + LogPagSeguro::info( + sprintf( + "PagSeguroTransactionSearchService.%s(initialDate=" . + PagSeguroHelper::formatDate($initialDate) . ", finalDate=" . + PagSeguroHelper::formatDate($finalDate) . ") - end ", + self::$logService + ) + . $searchResult->toString() + ); + break; + case 'BAD_REQUEST': + $errors = PagSeguroTransactionParser::readErrors($connection->getResponse()); + $err = new PagSeguroServiceException($httpStatus, $errors); + LogPagSeguro::error( + sprintf( + "PagSeguroTransactionSearchService.%s(initialDate=" . + PagSeguroHelper::formatDate($initialDate) . ", finalDate=" . + PagSeguroHelper::formatDate($finalDate) . ") - end ", + self::$logService + ) + . $err->getOneLineMessage() + ); + throw $err; + break; + default: + $err = new PagSeguroServiceException($httpStatus); + LogPagSeguro::error( + sprintf( + "PagSeguroTransactionSearchService.%s(initialDate=" . + PagSeguroHelper::formatDate($initialDate) . ", finalDate=" . + PagSeguroHelper::formatDate($finalDate) . ") - end ", + self::$logService + ) + . $err->getOneLineMessage() + ); + throw $err; + break; + } + + return isset($searchResult) ? $searchResult : false; + } +} diff --git a/PagSeguroLibrary/utils/PagSeguroHttpConnection.class.php b/PagSeguroLibrary/utils/PagSeguroHttpConnection.class.php new file mode 100644 index 0000000..d1b7ce7 --- /dev/null +++ b/PagSeguroLibrary/utils/PagSeguroHttpConnection.class.php @@ -0,0 +1,130 @@ +status; + } + + public function setStatus($status) + { + $this->status = $status; + } + + public function getResponse() + { + return $this->response; + } + + public function setResponse($response) + { + $this->response = $response; + } + + public function post($url, array $data = array(), $timeout = 20, $charset = 'ISO-8859-1') + { + return $this->curlConnection('POST', $url, $timeout, $charset, $data); + } + + public function get($url, $timeout = 20, $charset = 'ISO-8859-1') + { + return $this->curlConnection('GET', $url, $timeout, $charset, null); + } + + private function curlConnection($method, $url, $timeout, $charset, array $data = null) + { + + if (strtoupper($method) === 'POST') { + $postFields = ($data ? http_build_query($data, '', '&') : ""); + $contentLength = "Content-length: " . strlen($postFields); + $methodOptions = array( + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $postFields, + ); + } else { + $contentLength = null; + $methodOptions = array( + CURLOPT_HTTPGET => true + ); + } + + + $options = array( + CURLOPT_HTTPHEADER => array( + "Content-Type: application/x-www-form-urlencoded; charset=" . $charset, + $contentLength, + 'lib-description: php:' . PagSeguroLibrary::getVersion(), + 'language-engine-description: php:' . PagSeguroLibrary::getPHPVersion() + ), + CURLOPT_URL => $url, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HEADER => false, + CURLOPT_SSL_VERIFYPEER => false, + CURLOPT_CONNECTTIMEOUT => $timeout, + //CURLOPT_TIMEOUT => $timeout + ); + + if (!is_null(PagSeguroLibrary::getModuleVersion())) { + array_push($options[CURLOPT_HTTPHEADER], 'module-description: ' . PagSeguroLibrary::getModuleVersion()); + } + + if (!is_null(PagSeguroLibrary::getCMSVersion())) { + array_push($options[CURLOPT_HTTPHEADER], 'cms-description: ' . PagSeguroLibrary::getCMSVersion()); + } + + $options = ($options + $methodOptions); + + $curl = curl_init(); + curl_setopt_array($curl, $options); + $resp = curl_exec($curl); + $info = curl_getinfo($curl); + $error = curl_errno($curl); + $errorMessage = curl_error($curl); + curl_close($curl); + + $this->setStatus((int) $info['http_code']); + $this->setResponse((String) $resp); + + if ($error) { + throw new Exception("CURL can't connect: $errorMessage"); + } else { + return true; + } + } +} diff --git a/PagSeguroLibrary/utils/PagSeguroXmlParser.class.php b/PagSeguroLibrary/utils/PagSeguroXmlParser.class.php new file mode 100644 index 0000000..518acbe --- /dev/null +++ b/PagSeguroLibrary/utils/PagSeguroXmlParser.class.php @@ -0,0 +1,113 @@ +dom = new DOMDocument(); + $this->dom->loadXml($xml); + } + } + + public function getResult($node = null) + { + $result = $this->toArray($this->dom); + if ($node) { + if (isset($result[$node])) { + return $result[$node]; + } else { + throw new Exception("PagSeguroLibrary XML parsing error: undefined index [$node]"); + } + } else { + return $result; + } + } + + private function toArray($node) + { + $occurrence = array(); + $result = null; + /*** @var $node DOMNode */ + if ($node->hasChildNodes()) { + foreach ($node->childNodes as $child) { + if (!isset($occurrence[$child->nodeName])) { + $occurrence[$child->nodeName] = null; + } + $occurrence[$child->nodeName]++; + } + } + if (isset($child)) { + if ($child->nodeName == '#text') { + $result = html_entity_decode( + htmlentities($node->nodeValue, ENT_COMPAT, 'UTF-8'), + ENT_COMPAT, + 'ISO-8859-15' + ); + } else { + if ($node->hasChildNodes()) { + $children = $node->childNodes; + for ($i = 0; $i < $children->length; $i++) { + $child = $children->item($i); + if ($child->nodeName != '#text') { + if ($occurrence[$child->nodeName] > 1) { + $result[$child->nodeName][] = $this->toArray($child); + } else { + $result[$child->nodeName] = $this->toArray($child); + } + } else { + if ($child->nodeName == '0') { + $text = $this->toArray($child); + if (trim($text) != '') { + $result[$child->nodeName] = $this->toArray($child); + } + } + } + } + } + if ($node->hasAttributes()) { + $attributes = $node->attributes; + if (!is_null($attributes)) { + foreach ($attributes as $key => $attr) { + $result["@" . $attr->name] = $attr->value; + } + } + } + } + return $result; + } else { + return null; + } + } +} diff --git a/pagseguro_virtuemartbrasil.php b/pagseguro_virtuemartbrasil.php index 42be43b..a57332f 100644 --- a/pagseguro_virtuemartbrasil.php +++ b/pagseguro_virtuemartbrasil.php @@ -29,6 +29,10 @@ if (!class_exists('shopFunctions')) require(JPATH_VM_ADMINISTRATOR . DS . 'helpers' . DS . 'shopfunctions.php'); +if (!class_exists('PagSeguroLibrary')) { + require('PagSeguroLibrary/PagSeguroLibrary.php'); +} + class plgVmPaymentPagseguro_virtuemartbrasil extends vmPSPlugin { // instance of class @@ -623,105 +627,95 @@ public function plgVmOnPaymentNotification() { */ function plgVmOnPaymentNotification() { - header("Status: 200 OK"); + header("Status: 200 OK"); if (!class_exists('VirtueMartModelOrders')) require( JPATH_VM_ADMINISTRATOR . DS . 'models' . DS . 'orders.php' ); $pagseguro_data = $_REQUEST; if (!isset($pagseguro_data['TransacaoID'])) { return; - } - $order_number = $pagseguro_data['Referencia']; + } + + $this->logInfo('pagseguro_data ' . implode(' ', $pagseguro_data), 'message'); + + // dados do pagseguro + $email_cobranca = $method->email_cobranca; + $token = $method->token; + + $credentials = new PagSeguroAccountCredentials($merchant_email, $pagseguro_token); + + $type = $pagseguro_data['notificationType']; + $code = $pagseguro_data['notificationCode']; + + if ($type === 'transaction') { + $transaction = PagSeguroNotificationService::checkTransaction($credentials, $code); + } else { + return false; + } + + // dados do pedido + $referencia = $transaction->getReference(); + $PSdataRef = explode('|||', $referencia); + $order_number = $PSdataRef[0]; + $return_context = $PSdataRef[1]; $virtuemart_order_id = VirtueMartModelOrders::getOrderIdByOrderNumber($order_number); - //$this->logInfo('plgVmOnPaymentNotification: virtuemart_order_id found ' . $virtuemart_order_id, 'message'); if (!$virtuemart_order_id) { return; } $vendorId = 0; $payment = $this->getDataByOrderId($virtuemart_order_id); - if($payment->payment_name == '') { - return false; - } - $method = $this->getVmPluginMethod($payment->virtuemart_paymentmethod_id); - if (!$this->selectedThisElement($method->payment_element)) { - return false; - } - //$this->_debug = $method->debug; if (!$payment) { $this->logInfo('getDataByOrderId payment not found: exit ', 'ERROR'); return null; } - $this->logInfo('pagseguro_data ' . implode(' ', $pagseguro_data), 'message'); - // get all know columns of the table - $db = JFactory::getDBO(); - $query = 'SHOW COLUMNS FROM `' . $this->_tablename . '` '; - $db->setQuery($query); - $columns = $db->loadResultArray(0); - $post_msg = ''; - foreach ($pagseguro_data as $key => $value) { - $post_msg .= $key . "=" . $value . "
"; - $table_key = 'pagseguro_response_' . $key; - if (in_array($table_key, $columns)) { - $response_fields[$table_key] = $value; - } + $method = $this->getVmPluginMethod($payment->virtuemart_paymentmethod_id); + if (!$this->selectedThisElement($method->payment_element)) { + return false; } - //$response_fields[$this->_tablepkey] = $this->_getTablepkeyValue($virtuemart_order_id); - //$response_fields['payment_name'] = $this->renderPluginName($method); - //$response_fields['paypalresponse_raw'] = $post_msg; - //$return_context = $pagseguro_data['custom']; + $this->_debug = $method->debug; + $this->logInfo('Notification: pagseguro_data ' . implode(' | ', $pagseguro_data), 'message'); - $response_fields['payment_name'] = $payment->payment_name; - $response_fields['order_number'] = $order_number; - $response_fields['virtuemart_order_id'] = $virtuemart_order_id; + $this->_storePagseguroInternalData($method, $transaction, $virtuemart_order_id); - //$preload=true preload the data here too preserve not updated data - //$this->storePSPluginInternalData($response_fields, 'virtuemart_order_id', true); - - /* - $error_msg = $this->_processIPN($pagseguro_data, $method); - $this->logInfo('process IPN ' . $error_msg, 'message'); - if (!(empty($error_msg) )) { - $new_status = $method->status_canceled; - $this->logInfo('process IPN ' . $error_msg . ' ' . $new_status, 'ERROR'); - } else { - $this->logInfo('process IPN OK', 'message'); - }*/ - /* - * https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_IPNandPDTVariables - * The status of the payment: - * Canceled_Reversal: A reversal has been canceled. For example, you won a dispute with the customer, and the funds for the transaction that was reversed have been returned to you. - * Completed: The payment has been completed, and the funds have been added successfully to your account balance. - * Created: A German ELV payment is made using Express Checkout. - * Denied: You denied the payment. This happens only if the payment was previously pending because of possible reasons described for the pending_reason variable or the Fraud_Management_Filters_x variable. - * Expired: This authorization has expired and cannot be captured. - * Failed: The payment has failed. This happens only if the payment was made from your customer�s bank account. - * Pending: The payment is pending. See pending_reason for more information. - * Refunded: You refunded the payment. - * Reversed: A payment was reversed due to a chargeback or other type of reversal. The funds have been removed from your account balance and returned to the buyer. The reason for the reversal is specified in the ReasonCode element. - * Processed: A payment has been accepted. - * Voided: This authorization has been voided. - * - */ - if (empty($pagseguro_data['cod_status']) || ($pagseguro_data['cod_status'] != '0' && $pagseguro_data['cod_status'] != '1' && $pagseguro_data['cod_status'] != '2')) { - //return false; - } - - $pagseguro_status = $pagseguro_data['StatusTransacao']; - switch($pagseguro_status){ - case 'Completo': $new_status = $method->status_completo; break; - case 'Aprovado': $new_status = $method->status_aprovado; break; - case 'Em Análise': $new_status = $method->status_analise; break; - case 'Cancelado': $new_status = $method->status_cancelado; break; - case 'Paga': $new_status = $method->status_paga; break; - case 'Disponivel': $new_status = $method->status_disponivel; break; - case 'Devolvida': $new_status = $method->status_devolvida; break; - case 'Aguardando Pagto': - default: $new_status = $method->status_aguardando; break; - } + $ps_status = $transaction->getStatus(); + $payment_status = $ps_status->getValue(); + $order = array(); + $new_status = ''; + if ($payment_status == 1 || $payment_status == 2) { + $new_status = $method->status_aguardando; + $order['order_status'] = $new_status; + $order['customer_notified'] = 0; + $order['comments'] = 'O status do seu pedido '.$order_number.' no Pagseguro foi atualizado: Aguardando pagamento'; + } elseif ($payment_status == 3) { + $new_status = $method->status_aprovado; + $order['order_status'] = $new_status; + $order['customer_notified'] =1; + $order['comments'] = 'O status do seu pedido '.$order_number.' no Pagseguro foi atualizado: Pago'; + } elseif ($payment_status == 4) { + $new_status = $method->status_disponivel; + $order['order_status'] = $new_status; + $order['customer_notified'] =0; + $order['comments'] = 'O status do seu pedido '.$order_number.' no Pagseguro foi atualizado: Completo'; + } elseif ($payment_status == 5) { + $new_status = $method->status_analise; + $order['order_status'] = $new_status; + $order['customer_notified'] =0; + $order['comments'] = 'O status do seu pedido '.$order_number.' no Pagseguro foi atualizado: Disputa'; + } elseif ($payment_status == 6) { + $new_status = $method->status_devolvida; + $order['order_status'] = $new_status; + $order['customer_notified'] =0; + $order['comments'] = 'O status do seu pedido '.$order_number.' no Pagseguro foi atualizado: Devolvida'; + } elseif ($payment_status == 7) { + $new_status = $method->status_cancelado; + $order['order_status'] = $new_status; + $order['customer_notified'] =1; + $order['comments'] = 'O status do seu pedido '.$order_number.' no Pagseguro foi atualizado: Cancelada'; + } $this->logInfo('plgVmOnPaymentNotification return new_status:' . $new_status, 'message'); @@ -732,23 +726,16 @@ function plgVmOnPaymentNotification() { $modelOrder = new VirtueMartModelOrders(); $orderitems = $modelOrder->getOrder($virtuemart_order_id); $nb_history = count($orderitems['history']); - $order['order_status'] = $new_status; - $order['virtuemart_order_id'] = $virtuemart_order_id; - $order['comments'] = 'O status do seu pedido '.$order_number.' no Pagseguro foi atualizado: '.utf8_encode($pagseguro_data['StatusTransacao']); - if ($nb_history == 1) { - $order['comments'] .= "
" . JText::sprintf('VMPAYMENT_PAYPAL_EMAIL_SENT'); - $order['customer_notified'] = 0; - } else { - $order['customer_notified'] = 1; - } + $modelOrder->updateStatusForOneOrder($virtuemart_order_id, $order, true); if ($nb_history == 1) { - if (!class_exists('shopFunctionsF')) - require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php'); - shopFunctionsF::sentOrderConfirmedEmail($orderitems); - $this->logInfo('Notification, sentOrderConfirmedEmail ' . $order_number. ' '. $new_status, 'message'); + if (!class_exists('shopFunctionsF')) + require(JPATH_VM_SITE . DS . 'helpers' . DS . 'shopfunctionsf.php'); + shopFunctionsF::sentOrderConfirmedEmail($orderitems); + $this->logInfo('Notification, sentOrderConfirmedEmail ' . $order_number. ' '. $new_status, 'message'); } } + //// remove vmcart $this->emptyCart($return_context); } diff --git a/pagseguro_virtuemartbrasil.xml b/pagseguro_virtuemartbrasil.xml index be63880..03a524f 100644 --- a/pagseguro_virtuemartbrasil.xml +++ b/pagseguro_virtuemartbrasil.xml @@ -1,12 +1,12 @@ Pagseguro VirtueMart Brasil - Fevereiro 2015 + Novembro 2015 Fábio Paiva/Luiz F. Weber http://weber.eti.br - http://virtuemartbrasil.com.br Copyright (C) 2015. All rights reserved. http://www.gnu.org/licenses/gpl-3.0.html GNU/GPL - 2.8 + 2.9 Plugin de pagamento Pagseguro <div style="background:#E5F5FF;border:1px solid #99D6FF;padding:10px;margin:10px; -box-shadow: inset 0px 0px 10px #fff, 0px 0px 5px #ccc; -webkit-box-shadow: inset 0px 0px 10px #fff, 0px 0px 5px #ccc; -moz-box-shadow: inset 0px 0px 10px #fff, 0px 0px 5px #ccc;"> @@ -23,7 +23,7 @@ <div><em>Passo 3</em> - Na <b>aba configurações</b>, preencha os dados:</div> <div>* Logotipos: <b></b></div> <div>* Email Pagseguro: <b>Email da conta no Pagseguro</b></div> - <div>* Token: <b>Página inicial > Ferramentas > Preferências > Retorno automatico dos dados ( https://pagseguro.uol.com.br/preferences/automaticReturn.jhtml#rmcl ) </b></div> + <div>* Token: <b>Gerar o token no painel do Pagseguro</b> </div> <div>* Tipo de Frete Padrão: <b>( caso seja passado frete, esse parâmetro é desconsiderado)</b></div> <div><em>Status de Pedidos:</em></div> <div>* Completo: <b>Status transação Enviada</b></div> @@ -48,6 +48,7 @@ pagseguro_virtuemartbrasil.php imagens admin + PagSeguroLibrary logo_pagseguro2.jpg @@ -66,7 +67,7 @@ description="VMPAYMENT_STANDARD_LOGOS_TIP"/> - +