diff --git a/.gitignore b/.gitignore index bac603c2..40eaa506 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ build .DS_Store +phpunit.local.xml *.log # IDE diff --git a/lib/PayPal/Api/CreateProfileResponse.php b/lib/PayPal/Api/CreateProfileResponse.php index bdcae3fc..e086ba3b 100644 --- a/lib/PayPal/Api/CreateProfileResponse.php +++ b/lib/PayPal/Api/CreateProfileResponse.php @@ -3,7 +3,6 @@ namespace PayPal\Api; use PayPal\Common\PPModel; -use PayPal\Rest\ApiContext; /** * Class CreateProfileResponse diff --git a/lib/PayPal/Api/FlowConfig.php b/lib/PayPal/Api/FlowConfig.php index 3b046aa0..471322cb 100644 --- a/lib/PayPal/Api/FlowConfig.php +++ b/lib/PayPal/Api/FlowConfig.php @@ -3,7 +3,6 @@ namespace PayPal\Api; use PayPal\Common\PPModel; -use PayPal\Rest\ApiContext; use PayPal\Validation\UrlValidator; /** @@ -72,7 +71,7 @@ public function getLanding_page_type() * * * @param string $bank_txn_pending_url - * @throws InvalidArgumentException + * @throws \InvalidArgumentException * @return $this */ public function setBankTxnPendingUrl($bank_txn_pending_url) diff --git a/lib/PayPal/Api/InputFields.php b/lib/PayPal/Api/InputFields.php index 08ecfeb3..3e9b2472 100644 --- a/lib/PayPal/Api/InputFields.php +++ b/lib/PayPal/Api/InputFields.php @@ -3,7 +3,6 @@ namespace PayPal\Api; use PayPal\Common\PPModel; -use PayPal\Rest\ApiContext; /** * Class InputFields diff --git a/lib/PayPal/Api/Invoice.php b/lib/PayPal/Api/Invoice.php index 4988296b..65d84017 100644 --- a/lib/PayPal/Api/Invoice.php +++ b/lib/PayPal/Api/Invoice.php @@ -1,32 +1,19 @@ toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices", "POST", $payLoad); + $json = self::executeCall( + "/v1/invoicing/invoices", + "POST", + $payLoad, + $apiContext, + $restCall + ); $this->fromJson($json); return $this; } - /* + /** * Search for invoice resources. * * @param Search $search - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return Invoices */ - public function search($search, $apiContext = null) + public function search($search, $apiContext = null, $restCall = null) { ArgumentValidator::validate($search, 'search'); $payLoad = $search->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/search", "POST", $payLoad); + $json = self::executeCall( + "/v1/invoicing/search", + "POST", + $payLoad, + $apiContext, + $restCall + ); $ret = new Invoices(); $ret->fromJson($json); return $ret; } - /* + /** * Sends a legitimate invoice to the payer. * - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. - * @return void + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls + * @return bool */ - public function send($apiContext = null) + public function send($apiContext = null, $restCall = null) { - if ($this->getId() == null) { - throw new \InvalidArgumentException("Id cannot be null"); - } + ArgumentValidator::validate($this->getId(), "Id"); $payLoad = ""; - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/send", "POST", $payLoad); + self::executeCall( + "/v1/invoicing/invoices/{$this->getId()}/send", + "POST", + $payLoad, + $apiContext, + $restCall + ); return true; } - /* + /** * Reminds the payer to pay the invoice. * * @param Notification $notification - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. - * @return void + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls + * @return bool */ - public function remind($notification, $apiContext = null) + public function remind($notification, $apiContext = null, $restCall = null) { - if ($this->getId() == null) { - throw new \InvalidArgumentException("Id cannot be null"); - } - if (($notification == null)) { - throw new \InvalidArgumentException("notification cannot be null or empty"); - } + ArgumentValidator::validate($this->getId(), "Id"); + ArgumentValidator::validate($notification, "Notification"); $payLoad = $notification->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/remind", "POST", $payLoad); + self::executeCall( + "/v1/invoicing/invoices/{$this->getId()}/remind", + "POST", + $payLoad, + $apiContext, + $restCall + ); return true; } - /* + /** * Cancels an invoice. * * @param CancelNotification $cancelNotification - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. - * @return void + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls + * @return bool */ - public function cancel($cancelNotification, $apiContext = null) + public function cancel($cancelNotification, $apiContext = null, $restCall = null) { - if ($this->getId() == null) { - throw new \InvalidArgumentException("Id cannot be null"); - } - if (($cancelNotification == null)) { - throw new \InvalidArgumentException("cancelNotification cannot be null or empty"); - } + ArgumentValidator::validate($this->getId(), "Id"); + ArgumentValidator::validate($cancelNotification, "CancelNotification"); $payLoad = $cancelNotification->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/cancel", "POST", $payLoad); + self::executeCall( + "/v1/invoicing/invoices/{$this->getId()}/cancel", + "POST", + $payLoad, + $apiContext, + $restCall + ); return true; } - /* + /** * Mark the status of the invoice as paid. * * @param PaymentDetail $paymentDetail - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. - * @return void + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls + * @return bool */ - public function record_payment($paymentDetail, $apiContext = null) + public function record_payment($paymentDetail, $apiContext = null, $restCall = null) { - if ($this->getId() == null) { - throw new \InvalidArgumentException("Id cannot be null"); - } - if (($paymentDetail == null)) { - throw new \InvalidArgumentException("paymentDetail cannot be null or empty"); - } + ArgumentValidator::validate($this->getId(), "Id"); + ArgumentValidator::validate($paymentDetail, "PaymentDetail"); $payLoad = $paymentDetail->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/record-payment", "POST", $payLoad); + self::executeCall( + "/v1/invoicing/invoices/{$this->getId()}/record-payment", + "POST", + $payLoad, + $apiContext, + $restCall + ); return true; } - /* + /** * Mark the status of the invoice as refunded. * * @param RefundDetail $refundDetail - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. - * @return void + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls + * @return bool */ - public function record_refund($refundDetail, $apiContext = null) + public function record_refund($refundDetail, $apiContext = null, $restCall = null) { - if ($this->getId() == null) { - throw new \InvalidArgumentException("Id cannot be null"); - } - if (($refundDetail == null)) { - throw new \InvalidArgumentException("refundDetail cannot be null or empty"); - } + ArgumentValidator::validate($this->getId(), "Id"); + ArgumentValidator::validate($refundDetail, "RefundDetail"); $payLoad = $refundDetail->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/record-refund", "POST", $payLoad); + self::executeCall( + "/v1/invoicing/invoices/{$this->getId()}/record-refund", + "POST", + $payLoad, + $apiContext, + $restCall + ); return true; } - /* + /** * Get the invoice resource for the given identifier. * * @param string $invoiceId - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return Invoice */ - public static function get($invoiceId, $apiContext = null) + public static function get($invoiceId, $apiContext = null, $restCall = null) { - if (($invoiceId == null) || (strlen($invoiceId) <= 0)) { - throw new \InvalidArgumentException("invoiceId cannot be null or empty"); - } + ArgumentValidator::validate($invoiceId); $payLoad = ""; - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/$invoiceId", "GET", $payLoad); + $json = self::executeCall( + "/v1/invoicing/invoices/$invoiceId", + "GET", + $payLoad, + $apiContext, + $restCall + ); $ret = new Invoice(); $ret->fromJson($json); return $ret; } - /* + /** * Get all invoices of a merchant. * - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return Invoices */ - public static function get_all($apiContext = null) + public static function get_all($apiContext = null, $restCall = null) { $payLoad = ""; - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/", "GET", $payLoad); + $json = self::executeCall( + "/v1/invoicing/invoices/", + "GET", + $payLoad, + $apiContext, + $restCall + ); $ret = new Invoices(); $ret->fromJson($json); return $ret; } - /* + /** * Full update of the invoice resource for the given identifier. * - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return Invoice */ - public function update($apiContext = null) + public function update($apiContext = null, $restCall = null) { - if ($this->getId() == null) { - throw new \InvalidArgumentException("Id cannot be null"); - } + ArgumentValidator::validate($this->getId(), "Id"); $payLoad = $this->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}", "PUT", $payLoad); + $json = self::executeCall( + "/v1/invoicing/invoices/{$this->getId()}", + "PUT", + $payLoad, + $apiContext, + $restCall + ); $this->fromJson($json); return $this; } - /* + /** * Delete invoice resource for the given identifier. * - * @param PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. - * @return void + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls + * @return bool */ - public function delete($apiContext = null) + public function delete($apiContext = null, $restCall = null) { - if ($this->getId() == null) { - throw new \InvalidArgumentException("Id cannot be null"); - } + ArgumentValidator::validate($this->getId(), "Id"); $payLoad = ""; - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}", "DELETE", $payLoad); + self::executeCall( + "/v1/invoicing/invoices/{$this->getId()}", + "DELETE", + $payLoad, + $apiContext, + $restCall + ); return true; } } diff --git a/lib/PayPal/Api/Patch.php b/lib/PayPal/Api/Patch.php index d8fe6ae8..23502b73 100644 --- a/lib/PayPal/Api/Patch.php +++ b/lib/PayPal/Api/Patch.php @@ -3,7 +3,6 @@ namespace PayPal\Api; use PayPal\Common\PPModel; -use PayPal\Rest\ApiContext; /** * Class Patch @@ -14,7 +13,7 @@ * * @property string op * @property string path - * @property \PayPal\Api\object value + * @property mixed value * @property string from */ class Patch extends PPModel @@ -71,7 +70,7 @@ public function getPath() * New value to apply based on the operation. op=remove does not require value. * * - * @param \PayPal\Api\object $value + * @param mixed $value * * @return $this */ @@ -84,7 +83,7 @@ public function setValue($value) /** * New value to apply based on the operation. op=remove does not require value. * - * @return \PayPal\Api\object + * @return mixed */ public function getValue() { diff --git a/lib/PayPal/Api/Presentation.php b/lib/PayPal/Api/Presentation.php index 97ee0b05..a98ed709 100644 --- a/lib/PayPal/Api/Presentation.php +++ b/lib/PayPal/Api/Presentation.php @@ -3,7 +3,6 @@ namespace PayPal\Api; use PayPal\Common\PPModel; -use PayPal\Rest\ApiContext; /** * Class Presentation diff --git a/lib/PayPal/Api/WebProfile.php b/lib/PayPal/Api/WebProfile.php index ce924ab6..292975af 100644 --- a/lib/PayPal/Api/WebProfile.php +++ b/lib/PayPal/Api/WebProfile.php @@ -2,12 +2,11 @@ namespace PayPal\Api; -use PayPal\Common\PPModel; -use PayPal\Rest\ApiContext; -use PayPal\Rest\IResource; +use PayPal\Common\ResourceModel; +use PayPal\Validation\ArgumentValidator; use PayPal\Api\CreateProfileResponse; +use PayPal\Rest\ApiContext; use PayPal\Transport\PPRestCall; -use PayPal\Validation\ArgumentValidator; /** * Class WebProfile @@ -22,26 +21,8 @@ * @property \PayPal\Api\InputFields input_fields * @property \PayPal\Api\Presentation presentation */ -class WebProfile extends PPModel implements IResource +class WebProfile extends ResourceModel { - /** - * OAuth Credentials to use for this call - * - * @var \PayPal\Auth\OAuthTokenCredential $credential - */ - protected static $credential; - - /** - * Sets Credential - * - * @deprecated Pass ApiContext to create/get methods instead - * @param \PayPal\Auth\OAuthTokenCredential $credential - */ - public static function setCredential($credential) - { - self::$credential = $credential; - } - /** * ID of the web experience profile. * @@ -215,17 +196,21 @@ public function getPresentation() /** * Create a web experience profile by passing the name of the profile and other profile details in the request JSON to the request URI. * - * @param \PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return CreateProfileResponse */ - public function create($apiContext = null) + public function create($apiContext = null, $restCall = null) { $payLoad = $this->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/", "POST", $payLoad); + $json = self::executeCall( + "/v1/payment-experience/web-profiles/", + "POST", + $payLoad, + null, + $apiContext, + $restCall + ); $ret = new CreateProfileResponse(); $ret->fromJson($json); return $ret; @@ -234,18 +219,22 @@ public function create($apiContext = null) /** * Update a web experience profile by passing the ID of the profile to the request URI. In addition, pass the profile details in the request JSON. If your request does not include values for all profile detail fields, the previously set values for the omitted fields are removed by this operation. * - * @param \PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return bool */ - public function update($apiContext = null) + public function update($apiContext = null, $restCall = null) { ArgumentValidator::validate($this->getId(), "Id"); $payLoad = $this->toJSON(); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/{$this->getId()}", "PUT", $payLoad); + self::executeCall( + "/v1/payment-experience/web-profiles/{$this->getId()}", + "PUT", + $payLoad, + null, + $apiContext, + $restCall + ); return true; } @@ -253,23 +242,27 @@ public function update($apiContext = null) * Partially update an existing web experience profile by passing the ID of the profile to the request URI. In addition, pass a patch object in the request JSON that specifies the operation to perform, path of the profile location to update, and a new value if needed to complete the operation. * * @param Patch[] $patch - * @param \PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return bool */ - public function partial_update($patch, $apiContext = null) + public function partial_update($patch, $apiContext = null, $restCall = null) { ArgumentValidator::validate($this->getId(), "Id"); ArgumentValidator::validate($patch, 'patch'); + $payload = array(); foreach ($patch as $patchObject) { $payload[] = $patchObject->toArray(); } - $payLoad = json_encode($payload); - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/{$this->getId()}", "PATCH", $payLoad); + self::executeCall( + "/v1/payment-experience/web-profiles/{$this->getId()}", + "PATCH", + $payLoad, + null, + $apiContext, + $restCall + ); return true; } @@ -277,18 +270,22 @@ public function partial_update($patch, $apiContext = null) * Retrieve the details of a particular web experience profile by passing the ID of the profile to the request URI. * * @param string $profileId - * @param \PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return WebProfile */ - public static function get($profileId, $apiContext = null) + public static function get($profileId, $apiContext = null, $restCall = null) { ArgumentValidator::validate($profileId, 'profileId'); $payLoad = ""; - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/$profileId", "GET", $payLoad); + $json = self::executeCall( + "/v1/payment-experience/web-profiles/$profileId", + "GET", + $payLoad, + null, + $apiContext, + $restCall + ); $ret = new WebProfile(); $ret->fromJson($json); return $ret; @@ -297,35 +294,43 @@ public static function get($profileId, $apiContext = null) /** * Lists all web experience profiles that exist for a merchant (or subject). * - * @param \PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return WebProfile[] */ - public static function get_list($apiContext = null) + public static function get_list($apiContext = null, $restCall = null) { $payLoad = ""; - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/", "GET", $payLoad); + $json = self::executeCall( + "/v1/payment-experience/web-profiles/", + "GET", + $payLoad, + null, + $apiContext, + $restCall + ); return WebProfile::getList($json); } /** * Delete an existing web experience profile by passing the profile ID to the request URI. * - * @param \PayPal\Rest\ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials. + * @param PPRestCall $restCall is the Rest Call Service that is used to make rest calls * @return bool */ - public function delete($apiContext = null) + public function delete($apiContext = null, $restCall = null) { ArgumentValidator::validate($this->getId(), "Id"); $payLoad = ""; - if ($apiContext == null) { - $apiContext = new ApiContext(self::$credential); - } - $call = new PPRestCall($apiContext); - $json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/{$this->getId()}", "DELETE", $payLoad); + self::executeCall( + "/v1/payment-experience/web-profiles/{$this->getId()}", + "DELETE", + $payLoad, + null, + $apiContext, + $restCall + ); return true; } diff --git a/lib/PayPal/Auth/Openid/PPOpenIdAddress.php b/lib/PayPal/Auth/Openid/PPOpenIdAddress.php new file mode 100644 index 00000000..64486e74 --- /dev/null +++ b/lib/PayPal/Auth/Openid/PPOpenIdAddress.php @@ -0,0 +1,119 @@ +street_address = $street_address; + return $this; + } + + /** + * Full street address component, which may include house number, street name. + * + * @return string + */ + public function getStreetAddress() + { + return $this->street_address; + } + + /** + * City or locality component. + * + * @param string $locality + */ + public function setLocality($locality) + { + $this->locality = $locality; + return $this; + } + + /** + * City or locality component. + * + * @return string + */ + public function getLocality() + { + return $this->locality; + } + + /** + * State, province, prefecture or region component. + * + * @param string $region + */ + public function setRegion($region) + { + $this->region = $region; + return $this; + } + + /** + * State, province, prefecture or region component. + * + * @return string + */ + public function getRegion() + { + return $this->region; + } + + /** + * Zip code or postal code component. + * + * @param string $postal_code + */ + public function setPostalCode($postal_code) + { + $this->postal_code = $postal_code; + return $this; + } + + /** + * Zip code or postal code component. + * + * @return string + */ + public function getPostalCode() + { + return $this->postal_code; + } + + /** + * Country name component. + * + * @param string $country + */ + public function setCountry($country) + { + $this->country = $country; + return $this; + } + + /** + * Country name component. + * + * @return string + */ + public function getCountry() + { + return $this->country; + } + + +} diff --git a/lib/PayPal/Auth/Openid/PPOpenIdError.php b/lib/PayPal/Auth/Openid/PPOpenIdError.php new file mode 100644 index 00000000..53b54a2c --- /dev/null +++ b/lib/PayPal/Auth/Openid/PPOpenIdError.php @@ -0,0 +1,76 @@ +error = $error; + return $this; + } + + /** + * A single ASCII error code from the following enum. + * + * @return string + */ + public function getError() + { + return $this->error; + } + + /** + * A resource ID that indicates the starting resource in the returned results. + * + * @param string $error_description + */ + public function setErrorDescription($error_description) + { + $this->error_description = $error_description; + return $this; + } + + /** + * A resource ID that indicates the starting resource in the returned results. + * + * @return string + */ + public function getErrorDescription() + { + return $this->error_description; + } + + /** + * A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error. + * + * @param string $error_uri + */ + public function setErrorUri($error_uri) + { + $this->error_uri = $error_uri; + return $this; + } + + /** + * A URI identifying a human-readable web page with information about the error, used to provide the client developer with additional information about the error. + * + * @return string + */ + public function getErrorUri() + { + return $this->error_uri; + } + + +} diff --git a/lib/PayPal/Auth/Openid/PPOpenIdSession.php b/lib/PayPal/Auth/Openid/PPOpenIdSession.php new file mode 100644 index 00000000..598ca735 --- /dev/null +++ b/lib/PayPal/Auth/Openid/PPOpenIdSession.php @@ -0,0 +1,101 @@ +getConfig(); + + if ($apiContext->get($clientId)) { + $clientId = $apiContext->get($clientId); + } + $scope = count($scope) != 0 ? $scope : array('openid', 'profile', 'address', 'email', 'phone', + 'https://uri.paypal.com/services/paypalattributes', 'https://uri.paypal.com/services/expresscheckout'); + if (!in_array('openid', $scope)) { + $scope[] = 'openid'; + } + + $params = array( + 'client_id' => $clientId, + 'response_type' => 'code', + 'scope' => implode(" ", $scope), + 'redirect_uri' => $redirectUri + ); + + if ($nonce) { + $params['nonce'] = $nonce; + } + if ($state) { + $params['state'] = $state; + } + return sprintf("%s/v1/authorize?%s", self::getBaseUrl($config), http_build_query($params)); + } + + + /** + * Returns the URL to which the user must be redirected to + * logout from the OpenID provider (i.e. PayPal) + * + * @param string $redirectUri Uri on merchant website to where + * the user must be redirected to post logout + * @param string $idToken id_token from the TokenInfo object + * @param ApiContext $apiContext Optional API Context + * @return string logout URL + */ + public static function getLogoutUrl($redirectUri, $idToken, $apiContext = null) + { + + if (is_null($apiContext)) { + $apiContext = new ApiContext(); + } + $config = $apiContext->getConfig(); + + $params = array( + 'id_token' => $idToken, + 'redirect_uri' => $redirectUri, + 'logout' => 'true' + ); + return sprintf("%s/v1/endsession?%s", self::getBaseUrl($config), http_build_query($params)); + } + + /** + * Gets the base URL for the Redirect URI + * + * @param $config + * @return null|string + */ + private static function getBaseUrl($config) + { + + if (array_key_exists('openid.RedirectUri', $config)) { + return $config['openid.RedirectUri']; + } else if (array_key_exists('mode', $config)) { + switch (strtoupper($config['mode'])) { + case 'SANDBOX': + return PPConstants::OPENID_REDIRECT_SANDBOX_URL; + case 'LIVE': + return PPConstants::OPENID_REDIRECT_LIVE_URL; + } + } + return null; + } +} diff --git a/lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php b/lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php new file mode 100644 index 00000000..d1805843 --- /dev/null +++ b/lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php @@ -0,0 +1,230 @@ +scope = $scope; + return $this; + } + + /** + * OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED. + * + * @return string + */ + public function getScope() + { + return $this->scope; + } + + /** + * The access token issued by the authorization server. + * + * @param string $access_token + */ + public function setAccessToken($access_token) + { + $this->access_token = $access_token; + return $this; + } + + /** + * The access token issued by the authorization server. + * + * @return string + */ + public function getAccessToken() + { + return $this->access_token; + } + + /** + * The refresh token, which can be used to obtain new access tokens using the same authorization grant as described in OAuth2.0 RFC6749 in Section 6. + * + * @param string $refresh_token + */ + public function setRefreshToken($refresh_token) + { + $this->refresh_token = $refresh_token; + return $this; + } + + /** + * The refresh token, which can be used to obtain new access tokens using the same authorization grant as described in OAuth2.0 RFC6749 in Section 6. + * + * @return string + */ + public function getRefreshToken() + { + return $this->refresh_token; + } + + /** + * The type of the token issued as described in OAuth2.0 RFC6749 (Section 7.1). Value is case insensitive. + * + * @param string $token_type + */ + public function setTokenType($token_type) + { + $this->token_type = $token_type; + return $this; + } + + /** + * The type of the token issued as described in OAuth2.0 RFC6749 (Section 7.1). Value is case insensitive. + * + * @return string + */ + public function getTokenType() + { + return $this->token_type; + } + + /** + * The id_token is a session token assertion that denotes the user's authentication status + * + * @param string $id_token + */ + public function setIdToken($id_token) + { + $this->id_token = $id_token; + return $this; + } + + /** + * The id_token is a session token assertion that denotes the user's authentication status + * + * @return string + */ + public function getIdToken() + { + return $this->id_token; + } + + /** + * The lifetime in seconds of the access token. + * + * @param integer $expires_in + */ + public function setExpiresIn($expires_in) + { + $this->expires_in = $expires_in; + return $this; + } + + /** + * The lifetime in seconds of the access token. + * + * @return integer + */ + public function getExpiresIn() + { + return $this->expires_in; + } + + + /** + * Creates an Access Token from an Authorization Code. + * + * @path /v1/identity/openidconnect/tokenservice + * @method POST + * @param array $params (allowed values are client_id, client_secret, grant_type, code and redirect_uri) + * (required) client_id from developer portal + * (required) client_secret from developer portal + * (required) code is Authorization code previously received from the authorization server + * (required) redirect_uri Redirection endpoint that must match the one provided during the + * authorization request that ended in receiving the authorization code. + * (optional) grant_type is the Token grant type. Defaults to authorization_code + * @param string $clientId + * @param string $clientSecret + * @param ApiContext $apiContext Optional API Context + * @param PPRestCall $restCall + * @return PPOpenIdTokeninfo + */ + public static function createFromAuthorizationCode($params, $clientId = null, $clientSecret = null, $apiContext = null, $restCall = null) + { + static $allowedParams = array('grant_type' => 1, 'code' => 1, 'redirect_uri' => 1); + + if (!array_key_exists('grant_type', $params)) { + $params['grant_type'] = 'authorization_code'; + } + + if ($apiContext->get('client_id')) { + $clientId = $apiContext->get('client_id'); + } + + if ($apiContext->get('client_secret')) { + $clientSecret = $apiContext->get('client_secret'); + } + $json = self::executeCall( + "/v1/identity/openidconnect/tokenservice", + "POST", + http_build_query(array_intersect_key($params, $allowedParams)), + array( + 'Content-Type' => 'application/x-www-form-urlencoded', + 'Authorization' => 'Basic ' . base64_encode($clientId . ":" . $clientSecret) + ), + $apiContext, + $restCall + ); + $token = new PPOpenIdTokeninfo(); + $token->fromJson($json); + return $token; + } + + /** + * Creates an Access Token from an Refresh Token. + * + * @path /v1/identity/openidconnect/tokenservice + * @method POST + * @param array $params (allowed values are grant_type and scope) + * (required) client_id from developer portal + * (required) client_secret from developer portal + * (optional) refresh_token refresh token. If one is not passed, refresh token from the current object is used. + * (optional) grant_type is the Token grant type. Defaults to refresh_token + * (optional) scope is an array that either the same or a subset of the scope passed to the authorization request + * @param APIContext $apiContext Optional API Context + * @return PPOpenIdTokeninfo + */ + public function createFromRefreshToken($params, $apiContext = null) + { + static $allowedParams = array('grant_type' => 1, 'refresh_token' => 1, 'scope' => 1); + + if (!array_key_exists('grant_type', $params)) { + $params['grant_type'] = 'refresh_token'; + } + if (!array_key_exists('refresh_token', $params)) { + $params['refresh_token'] = $this->getRefreshToken(); + } + + $json = self::executeCall( + "/v1/identity/openidconnect/tokenservice", + "POST", + http_build_query(array_intersect_key($params, $allowedParams)), + array( + 'Content-Type' => 'application/x-www-form-urlencoded', + 'Authorization' => 'Basic ' . base64_encode($params['client_id'] . ":" . $params['client_secret']) + ), + $apiContext + ); + + $this->fromJson($json); + return $this; + } +} diff --git a/lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php b/lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php new file mode 100644 index 00000000..e7d0544d --- /dev/null +++ b/lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php @@ -0,0 +1,491 @@ +user_id = $user_id; + return $this; + } + + /** + * Subject - Identifier for the End-User at the Issuer. + * + * @return string + */ + public function getUserId() + { + return $this->user_id; + } + + /** + * Subject - Identifier for the End-User at the Issuer. + * + * @param string $sub + */ + public function setSub($sub) + { + $this->sub = $sub; + return $this; + } + + /** + * Subject - Identifier for the End-User at the Issuer. + * + * @return string + */ + public function getSub() + { + return $this->sub; + } + + /** + * End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences. + * + * @param string $name + */ + public function setName($name) + { + $this->name = $name; + return $this; + } + + /** + * End-User's full name in displayable form including all name parts, possibly including titles and suffixes, ordered according to the End-User's locale and preferences. + * + * @return string + */ + public function getName() + { + return $this->name; + } + + /** + * Given name(s) or first name(s) of the End-User + * + * @param string $given_name + */ + public function setGivenName($given_name) + { + $this->given_name = $given_name; + return $this; + } + + /** + * Given name(s) or first name(s) of the End-User + * + * @return string + */ + public function getGivenName() + { + return $this->given_name; + } + + /** + * Surname(s) or last name(s) of the End-User. + * + * @param string $family_name + */ + public function setFamilyName($family_name) + { + $this->family_name = $family_name; + return $this; + } + + /** + * Surname(s) or last name(s) of the End-User. + * + * @return string + */ + public function getFamilyName() + { + return $this->family_name; + } + + /** + * Middle name(s) of the End-User. + * + * @param string $middle_name + */ + public function setMiddleName($middle_name) + { + $this->middle_name = $middle_name; + return $this; + } + + /** + * Middle name(s) of the End-User. + * + * @return string + */ + public function getMiddleName() + { + return $this->middle_name; + } + + /** + * URL of the End-User's profile picture. + * + * @param string $picture + */ + public function setPicture($picture) + { + $this->picture = $picture; + return $this; + } + + /** + * URL of the End-User's profile picture. + * + * @return string + */ + public function getPicture() + { + return $this->picture; + } + + /** + * End-User's preferred e-mail address. + * + * @param string $email + */ + public function setEmail($email) + { + $this->email = $email; + return $this; + } + + /** + * End-User's preferred e-mail address. + * + * @return string + */ + public function getEmail() + { + return $this->email; + } + + /** + * True if the End-User's e-mail address has been verified; otherwise false. + * + * @param boolean $email_verified + */ + public function setEmailVerified($email_verified) + { + $this->email_verified = $email_verified; + return $this; + } + + /** + * True if the End-User's e-mail address has been verified; otherwise false. + * + * @return boolean + */ + public function getEmailVerified() + { + return $this->email_verified; + } + + /** + * End-User's gender. + * + * @param string $gender + */ + public function setGender($gender) + { + $this->gender = $gender; + return $this; + } + + /** + * End-User's gender. + * + * @return string + */ + public function getGender() + { + return $this->gender; + } + + /** + * End-User's birthday, represented as an YYYY-MM-DD format. They year MAY be 0000, indicating it is omited. To represent only the year, YYYY format would be used. + * + * @param string $birthday + */ + public function setBirthday($birthday) + { + $this->birthday = $birthday; + return $this; + } + + /** + * End-User's birthday, represented as an YYYY-MM-DD format. They year MAY be 0000, indicating it is omited. To represent only the year, YYYY format would be used. + * + * @return string + */ + public function getBirthday() + { + return $this->birthday; + } + + /** + * Time zone database representing the End-User's time zone + * + * @param string $zoneinfo + */ + public function setZoneinfo($zoneinfo) + { + $this->zoneinfo = $zoneinfo; + return $this; + } + + /** + * Time zone database representing the End-User's time zone + * + * @return string + */ + public function getZoneinfo() + { + return $this->zoneinfo; + } + + /** + * End-User's locale. + * + * @param string $locale + */ + public function setLocale($locale) + { + $this->locale = $locale; + return $this; + } + + /** + * End-User's locale. + * + * @return string + */ + public function getLocale() + { + return $this->locale; + } + + /** + * End-User's language. + * + * @param string $language + */ + public function setLanguage($language) + { + $this->language = $language; + return $this; + } + + /** + * End-User's language. + * + * @return string + */ + public function getLanguage() + { + return $this->language; + } + + /** + * End-User's verified status. + * + * @param boolean $verified + */ + public function setVerified($verified) + { + $this->verified = $verified; + return $this; + } + + /** + * End-User's verified status. + * + * @return boolean + */ + public function getVerified() + { + return $this->verified; + } + + /** + * End-User's preferred telephone number. + * + * @param string $phone_number + */ + public function setPhoneNumber($phone_number) + { + $this->phone_number = $phone_number; + return $this; + } + + /** + * End-User's preferred telephone number. + * + * @return string + */ + public function getPhoneNumber() + { + return $this->phone_number; + } + + /** + * End-User's preferred address. + * + * @param \PayPal\Auth\Openid\PPOpenIdAddress $address + */ + public function setAddress($address) + { + $this->address = $address; + return $this; + } + + /** + * End-User's preferred address. + * + * @return \PayPal\Auth\Openid\PPOpenIdAddress + */ + public function getAddress() + { + return $this->address; + } + + /** + * Verified account status. + * + * @param boolean $verified_account + */ + public function setVerifiedAccount($verified_account) + { + $this->verified_account = $verified_account; + return $this; + } + + /** + * Verified account status. + * + * @return boolean + */ + public function getVerifiedAccount() + { + return $this->verified_account; + } + + /** + * Account type. + * + * @param string $account_type + */ + public function setAccountType($account_type) + { + $this->account_type = $account_type; + return $this; + } + + /** + * Account type. + * + * @return string + */ + public function getAccountType() + { + return $this->account_type; + } + + /** + * Account holder age range. + * + * @param string $age_range + */ + public function setAgeRange($age_range) + { + $this->age_range = $age_range; + return $this; + } + + /** + * Account holder age range. + * + * @return string + */ + public function getAgeRange() + { + return $this->age_range; + } + + /** + * Account payer identifier. + * + * @param string $payer_id + */ + public function setPayerId($payer_id) + { + $this->payer_id = $payer_id; + return $this; + } + + /** + * Account payer identifier. + * + * @return string + */ + public function getPayerId() + { + return $this->payer_id; + } + + + /** + * returns user details + * + * @path /v1/identity/openidconnect/userinfo + * @method GET + * @param array $params (allowed values are access_token) + * access_token - access token from the createFromAuthorizationCode / createFromRefreshToken calls + * @param ApiContext $apiContext Optional API Context + * @return PPOpenIdUserinfo + */ + public static function getUserinfo($params, $apiContext = null) + { + static $allowedParams = array('schema' => 1); + + if (!array_key_exists('schema', $params)) { + $params['schema'] = 'openid'; + } + $requestUrl = "/v1/identity/openidconnect/userinfo?" + . http_build_query(array_intersect_key($params, $allowedParams)); + + $json = self::executeCall( + $requestUrl, + "GET", + "", + array( + 'Authorization' => "Bearer " . $params['access_token'], + 'Content-Type' => 'x-www-form-urlencoded' + ), + $apiContext + ); + + $ret = new PPOpenIdUserinfo(); + $ret->fromJson($json); + + return $ret; + } +} diff --git a/lib/PayPal/Common/PPModel.php b/lib/PayPal/Common/PPModel.php index 5ac48d2c..bb33d68c 100644 --- a/lib/PayPal/Common/PPModel.php +++ b/lib/PayPal/Common/PPModel.php @@ -158,7 +158,7 @@ public function fromArray($arr) /** @var self $o */ $o = new $clazz(); $o->fromArray($v); - $this->setValue($k, $o); + $this->assignValue($k, $o); } else { $arr = array(); foreach ($v as $nk => $nv) { @@ -170,7 +170,7 @@ public function fromArray($arr) $arr[$nk] = $nv; } } - $this->setValue($k, $arr); + $this->assignValue($k, $arr); } } else { $this->$k = $v; @@ -179,7 +179,7 @@ public function fromArray($arr) return $this; } - private function setValue($key, $value) + private function assignValue($key, $value) { if (ModelAccessorValidator::validate($this, $this->convertToCamelCase($key))) { $setter = "set" . $this->convertToCamelCase($key); diff --git a/lib/PayPal/Common/ResourceModel.php b/lib/PayPal/Common/ResourceModel.php new file mode 100644 index 00000000..97e941c8 --- /dev/null +++ b/lib/PayPal/Common/ResourceModel.php @@ -0,0 +1,60 @@ +execute($handlers, $url, $method, $payLoad, $headers); + return $json; + } +} diff --git a/lib/PayPal/Core/PPConstants.php b/lib/PayPal/Core/PPConstants.php index 2f97e224..c21253bb 100644 --- a/lib/PayPal/Core/PPConstants.php +++ b/lib/PayPal/Core/PPConstants.php @@ -15,5 +15,8 @@ class PPConstants const SDK_VERSION = '0.11.0'; const REST_SANDBOX_ENDPOINT = "https://api.sandbox.paypal.com/"; + const OPENID_REDIRECT_SANDBOX_URL = "https://www.sandbox.paypal.com/webapps/auth/protocol/openidconnect"; + const REST_LIVE_ENDPOINT = "https://api.paypal.com/"; + const OPENID_REDIRECT_LIVE_URL = "https://www.paypal.com/webapps/auth/protocol/openidconnect"; } diff --git a/lib/PayPal/Rest/ApiContext.php b/lib/PayPal/Rest/ApiContext.php index f1c18782..c914bf9f 100644 --- a/lib/PayPal/Rest/ApiContext.php +++ b/lib/PayPal/Rest/ApiContext.php @@ -1,130 +1,131 @@ -credential == null) { - return PPCredentialManager::getInstance()->getCredentialObject(); - } - return $this->credential; - } - - /** - * Get Request ID - * - * @return string - */ - public function getrequestId() - { - if ($this->requestId == null) { - $this->requestId = $this->generateRequestId(); - } - - return $this->requestId; - } - - /** - * Construct - * - * @param \PayPal\Auth\OAuthTokenCredential $credential - * @param string|null $requestId - */ - public function __construct($credential = null, $requestId = null) - { - $this->requestId = $requestId; - $this->credential = $credential; - } - - /** - * Sets Config - * - * @param array $config SDK configuration parameters - */ - public function setConfig(array $config) - { - PPConfigManager::getInstance()->addConfigs($config); - } - - /** - * Gets Configurations - * - * @return array - */ - public function getConfig() - { - return PPConfigManager::getInstance()->getConfigHashmap(); - } - - /** - * Gets a specific configuration from key - * - * @param $searchKey - */ - public function get($searchKey) - { - PPConfigManager::getInstance()->get($searchKey); - } - - /** - * Generates a unique per request id that - * can be used to set the PayPal-Request-Id header - * that is used for idempotency - * - * @return string - */ - private function generateRequestId() - { - static $pid = -1; - static $addr = -1; - - if ($pid == -1) { - $pid = getmypid(); - } - - if ($addr == -1) { - if (array_key_exists('SERVER_ADDR', $_SERVER)) { - $addr = ip2long($_SERVER['SERVER_ADDR']); - } else { - $addr = php_uname('n'); - } - } - - return $addr . $pid . $_SERVER['REQUEST_TIME'] . mt_rand(0, 0xffff); - } -} +credential == null) { + return PPCredentialManager::getInstance()->getCredentialObject(); + } + return $this->credential; + } + + /** + * Get Request ID + * + * @return string + */ + public function getrequestId() + { + if ($this->requestId == null) { + $this->requestId = $this->generateRequestId(); + } + + return $this->requestId; + } + + /** + * Construct + * + * @param \PayPal\Auth\OAuthTokenCredential $credential + * @param string|null $requestId + */ + public function __construct($credential = null, $requestId = null) + { + $this->requestId = $requestId; + $this->credential = $credential; + } + + /** + * Sets Config + * + * @param array $config SDK configuration parameters + */ + public function setConfig(array $config) + { + PPConfigManager::getInstance()->addConfigs($config); + } + + /** + * Gets Configurations + * + * @return array + */ + public function getConfig() + { + return PPConfigManager::getInstance()->getConfigHashmap(); + } + + /** + * Gets a specific configuration from key + * + * @param $searchKey + * @return mixed + */ + public function get($searchKey) + { + return PPConfigManager::getInstance()->get($searchKey); + } + + /** + * Generates a unique per request id that + * can be used to set the PayPal-Request-Id header + * that is used for idempotency + * + * @return string + */ + private function generateRequestId() + { + static $pid = -1; + static $addr = -1; + + if ($pid == -1) { + $pid = getmypid(); + } + + if ($addr == -1) { + if (array_key_exists('SERVER_ADDR', $_SERVER)) { + $addr = ip2long($_SERVER['SERVER_ADDR']); + } else { + $addr = php_uname('n'); + } + } + + return $addr . $pid . $_SERVER['REQUEST_TIME'] . mt_rand(0, 0xffff); + } +} diff --git a/lib/PayPal/Rest/RestHandler.php b/lib/PayPal/Rest/RestHandler.php index 63bfe439..8ec134ca 100644 --- a/lib/PayPal/Rest/RestHandler.php +++ b/lib/PayPal/Rest/RestHandler.php @@ -1,132 +1,132 @@ -apiContext = $apiContext; - } - - /** - * @param \Paypal\Core\PPHttpConfig $httpConfig - * @param string $request - * @param mixed $options - * @return mixed|void - * @throws PPConfigurationException - * @throws PPInvalidCredentialException - * @throws PPMissingCredentialException - */ - public function handle($httpConfig, $request, $options) - { - - $credential = $this->apiContext->getCredential(); - $config = $this->apiContext->getConfig(); - - if ($credential == null) { - // Try picking credentials from the config file - $credMgr = PPCredentialManager::getInstance($config); - $credValues = $credMgr->getCredentialObject(); - - if (!is_array($credValues)) { - throw new PPMissingCredentialException("Empty or invalid credentials passed"); - } - - $credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']); - } - - if ($credential == null || !($credential instanceof OAuthTokenCredential)) { - throw new PPInvalidCredentialException("Invalid credentials passed"); - } - - $httpConfig->setUrl( - rtrim(trim($this->_getEndpoint($config)), '/') . - (isset($options['path']) ? $options['path'] : '') - ); - - if (!array_key_exists("User-Agent", $httpConfig->getHeaders())) { - $httpConfig->addHeader("User-Agent", PPUserAgent::getValue(self::$sdkName, self::$sdkVersion)); - } - - if (!is_null($credential) && $credential instanceof OAuthTokenCredential) { - $httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config)); - } - - if ($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') { - $httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId()); - } - } - - /** - * End Point - * - * @param array $config - * - * @return string - * @throws \PayPal\Exception\PPConfigurationException - */ - private function _getEndpoint($config) - { - if (isset($config['service.EndPoint'])) { - return $config['service.EndPoint']; - } else if (isset($config['mode'])) { - switch (strtoupper($config['mode'])) { - case 'SANDBOX': - return PPConstants::REST_SANDBOX_ENDPOINT; - break; - case 'LIVE': - return PPConstants::REST_LIVE_ENDPOINT; - break; - default: - throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live'); - break; - } - } else { - throw new PPConfigurationException( - 'You must set one of service.endpoint or mode parameters in your configuration' - ); - } - } -} +apiContext = $apiContext; + } + + /** + * @param \Paypal\Core\PPHttpConfig $httpConfig + * @param string $request + * @param mixed $options + * @return mixed|void + * @throws PPConfigurationException + * @throws PPInvalidCredentialException + * @throws PPMissingCredentialException + */ + public function handle($httpConfig, $request, $options) + { + + $credential = $this->apiContext->getCredential(); + $config = $this->apiContext->getConfig(); + + if ($credential == null) { + // Try picking credentials from the config file + $credMgr = PPCredentialManager::getInstance($config); + $credValues = $credMgr->getCredentialObject(); + + if (!is_array($credValues)) { + throw new PPMissingCredentialException("Empty or invalid credentials passed"); + } + + $credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']); + } + + if ($credential == null || !($credential instanceof OAuthTokenCredential)) { + throw new PPInvalidCredentialException("Invalid credentials passed"); + } + + $httpConfig->setUrl( + rtrim(trim($this->_getEndpoint($config)), '/') . + (isset($options['path']) ? $options['path'] : '') + ); + + if (!array_key_exists("User-Agent", $httpConfig->getHeaders())) { + $httpConfig->addHeader("User-Agent", PPUserAgent::getValue(self::$sdkName, self::$sdkVersion)); + } + + if (!is_null($credential) && $credential instanceof OAuthTokenCredential && is_null($httpConfig->getHeader('Authorization'))) { + $httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config), false); + } + + if ($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') { + $httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId()); + } + } + + /** + * End Point + * + * @param array $config + * + * @return string + * @throws \PayPal\Exception\PPConfigurationException + */ + private function _getEndpoint($config) + { + if (isset($config['service.EndPoint'])) { + return $config['service.EndPoint']; + } else if (isset($config['mode'])) { + switch (strtoupper($config['mode'])) { + case 'SANDBOX': + return PPConstants::REST_SANDBOX_ENDPOINT; + break; + case 'LIVE': + return PPConstants::REST_LIVE_ENDPOINT; + break; + default: + throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live'); + break; + } + } else { + throw new PPConfigurationException( + 'You must set one of service.endpoint or mode parameters in your configuration' + ); + } + } +} diff --git a/lib/PayPal/Transport/PPRestCall.php b/lib/PayPal/Transport/PPRestCall.php index 312fffce..ab9b12a0 100644 --- a/lib/PayPal/Transport/PPRestCall.php +++ b/lib/PayPal/Transport/PPRestCall.php @@ -4,6 +4,7 @@ use PayPal\Core\PPLoggingManager; use PayPal\Core\PPHttpConfig; use PayPal\Core\PPHttpConnection; +use PayPal\Rest\ApiContext; /** * Class PPRestCall @@ -24,7 +25,7 @@ class PPRestCall /** * API Context * - * @var \Paypal\Rest\ApiContext + * @var ApiContext */ private $apiContext; @@ -32,9 +33,9 @@ class PPRestCall /** * Default Constructor * - * @param \Paypal\Rest\ApiContext $apiContext + * @param ApiContext $apiContext */ - public function __construct(\Paypal\Rest\ApiContext $apiContext) + public function __construct(ApiContext $apiContext) { $this->apiContext = $apiContext; $this->logger = PPLoggingManager::getInstance(__CLASS__); @@ -54,6 +55,7 @@ public function execute($handlers = array(), $path, $method, $data = '', $header $config = $this->apiContext->getConfig(); $httpConfig = new PPHttpConfig(null, $method); + $headers = $headers ? $headers : array(); $httpConfig->setHeaders($headers + array( 'Content-Type' => 'application/json' diff --git a/phpunit.integration.xml b/phpunit.integration.xml index 3738b96d..e2c59281 100644 --- a/phpunit.integration.xml +++ b/phpunit.integration.xml @@ -9,6 +9,10 @@ convertWarningsToExceptions="true" testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"> + + + + tests @@ -29,4 +33,4 @@ - \ No newline at end of file + diff --git a/release_notes.md b/release_notes.md index f949f3ea..b4640bdc 100644 --- a/release_notes.md +++ b/release_notes.md @@ -1,6 +1,10 @@ PayPal PHP SDK release notes ============================ +v0.13.1 +---- +* Updated Identity Support from SDK Core + v0.13.0 ---- * Enabled Payment Experience diff --git a/sample/payments/CreateOpenID.php b/sample/payments/CreateOpenID.php new file mode 100644 index 00000000..30e92587 --- /dev/null +++ b/sample/payments/CreateOpenID.php @@ -0,0 +1,23 @@ +/execute'. + +require __DIR__ . '/../bootstrap.php'; + +$clientId = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS'; +$clientSecret = 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL'; + +use PayPal\Api\ExecutePayment; +use PayPal\Api\Payment; +use PayPal\Api\PaymentExecution; +session_start(); +if(isset($_GET['success']) && $_GET['success'] == 'true') { + + + $code = $_GET['code']; + + $params = array( + 'code' => $code, + 'redirect_uri' => getBaseUrl() . '/ExecuteAuth.php?success=true', + 'client_id' => $clientId, + 'client_secret' => $clientSecret + ); + try { + $accessToken = \PayPal\Auth\Openid\PPOpenIdTokeninfo::createFromAuthorizationCode($params, $clientId, $clientSecret, $apiContext); + } catch (PayPal\Exception\PPConnectionException $ex) { + echo "Exception: " . $ex->getMessage() . PHP_EOL; + var_dump($ex->getData()); + exit(1); + } + echo $accessToken->toJSON(JSON_PRETTY_PRINT); + +} diff --git a/tests/PayPal/Test/Api/CreateProfileResponseTest.php b/tests/PayPal/Test/Api/CreateProfileResponseTest.php new file mode 100644 index 00000000..5656eb65 --- /dev/null +++ b/tests/PayPal/Test/Api/CreateProfileResponseTest.php @@ -0,0 +1,78 @@ +assertNotNull($obj); + $this->assertNotNull($obj->getId()); + $this->assertEquals(self::getJson(), $obj->toJson()); + return $obj; + } + + /** + * @depends testSerializationDeserialization + * @param CreateProfileResponse $obj + */ + public function testGetters($obj) + { + $this->assertEquals($obj->getId(), "TestSample"); + } + + /** + * @depends testSerializationDeserialization + * @param CreateProfileResponse $obj + */ + public function testDeprecatedGetters($obj) + { + } + + /** + * @depends testSerializationDeserialization + * @param CreateProfileResponse $obj + */ + public function testDeprecatedSetterNormalGetter($obj) + { + + //Test All Deprecated Getters and Normal Getters + $this->testDeprecatedGetters($obj); + $this->testGetters($obj); + } + + + +} diff --git a/tests/PayPal/Test/Api/FlowConfigTest.php b/tests/PayPal/Test/Api/FlowConfigTest.php new file mode 100644 index 00000000..cd8d20e1 --- /dev/null +++ b/tests/PayPal/Test/Api/FlowConfigTest.php @@ -0,0 +1,105 @@ +assertNotNull($obj); + $this->assertNotNull($obj->getLandingPageType()); + $this->assertNotNull($obj->getBankTxnPendingUrl()); + $this->assertEquals(self::getJson(), $obj->toJson()); + return $obj; + } + + /** + * @depends testSerializationDeserialization + * @param FlowConfig $obj + */ + public function testGetters($obj) + { + $this->assertEquals($obj->getLandingPageType(), "TestSample"); + $this->assertEquals($obj->getBankTxnPendingUrl(), "http://www.google.com"); + } + + /** + * @depends testSerializationDeserialization + * @param FlowConfig $obj + */ + public function testDeprecatedGetters($obj) + { + $this->assertEquals($obj->getLanding_page_type(), "TestSample"); + $this->assertEquals($obj->getBank_txn_pending_url(), "http://www.google.com"); + } + + /** + * @depends testSerializationDeserialization + * @param FlowConfig $obj + */ + public function testDeprecatedSetterNormalGetter($obj) + { + + // Check for Landing_page_type + $obj->setLandingPageType(null); + $this->assertNull($obj->getLanding_page_type()); + $this->assertNull($obj->getLandingPageType()); + $this->assertSame($obj->getLandingPageType(), $obj->getLanding_page_type()); + $obj->setLanding_page_type("TestSample"); + $this->assertEquals($obj->getLanding_page_type(), "TestSample"); + + //Test All Deprecated Getters and Normal Getters + $this->testDeprecatedGetters($obj); + $this->testGetters($obj); + } + + /** + * @expectedException \InvalidArgumentException + * @expectedExceptionMessage BankTxnPendingUrl is not a fully qualified URL + */ + public function testUrlValidationForBankTxnPendingUrl() + { + $obj = new FlowConfig(); + $obj->setBankTxnPendingUrl(null); + } + + public function testUrlValidationForBankTxnPendingUrlDeprecated() + { + $obj = new FlowConfig(); + $obj->setBank_txn_pending_url(null); + $this->assertNull($obj->getBank_txn_pending_url()); + } + +} diff --git a/tests/PayPal/Test/Api/InputFieldsTest.php b/tests/PayPal/Test/Api/InputFieldsTest.php new file mode 100644 index 00000000..a19be986 --- /dev/null +++ b/tests/PayPal/Test/Api/InputFieldsTest.php @@ -0,0 +1,109 @@ +assertNotNull($obj); + $this->assertNotNull($obj->getAllowNote()); + $this->assertNotNull($obj->getNoShipping()); + $this->assertNotNull($obj->getAddressOverride()); + $this->assertEquals(self::getJson(), $obj->toJson()); + return $obj; + } + + /** + * @depends testSerializationDeserialization + * @param InputFields $obj + */ + public function testGetters($obj) + { + $this->assertEquals($obj->getAllowNote(), true); + $this->assertEquals($obj->getNoShipping(), 123); + $this->assertEquals($obj->getAddressOverride(), 123); + } + + /** + * @depends testSerializationDeserialization + * @param InputFields $obj + */ + public function testDeprecatedGetters($obj) + { + $this->assertEquals($obj->getAllow_note(), true); + $this->assertEquals($obj->getNo_shipping(), 123); + $this->assertEquals($obj->getAddress_override(), 123); + } + + /** + * @depends testSerializationDeserialization + * @param InputFields $obj + */ + public function testDeprecatedSetterNormalGetter($obj) + { + + // Check for Allow_note + $obj->setAllowNote(null); + $this->assertNull($obj->getAllow_note()); + $this->assertNull($obj->getAllowNote()); + $this->assertSame($obj->getAllowNote(), $obj->getAllow_note()); + $obj->setAllow_note(true); + $this->assertEquals($obj->getAllow_note(), true); + + // Check for No_shipping + $obj->setNoShipping(null); + $this->assertNull($obj->getNo_shipping()); + $this->assertNull($obj->getNoShipping()); + $this->assertSame($obj->getNoShipping(), $obj->getNo_shipping()); + $obj->setNo_shipping(123); + $this->assertEquals($obj->getNo_shipping(), 123); + + // Check for Address_override + $obj->setAddressOverride(null); + $this->assertNull($obj->getAddress_override()); + $this->assertNull($obj->getAddressOverride()); + $this->assertSame($obj->getAddressOverride(), $obj->getAddress_override()); + $obj->setAddress_override(123); + $this->assertEquals($obj->getAddress_override(), 123); + + //Test All Deprecated Getters and Normal Getters + $this->testDeprecatedGetters($obj); + $this->testGetters($obj); + } + + + +} diff --git a/tests/PayPal/Test/Api/PatchTest.php b/tests/PayPal/Test/Api/PatchTest.php new file mode 100644 index 00000000..94ecb08e --- /dev/null +++ b/tests/PayPal/Test/Api/PatchTest.php @@ -0,0 +1,84 @@ +assertNotNull($obj); + $this->assertNotNull($obj->getOp()); + $this->assertNotNull($obj->getPath()); + $this->assertNotNull($obj->getValue()); + $this->assertNotNull($obj->getFrom()); + $this->assertEquals(self::getJson(), $obj->toJson()); + return $obj; + } + + /** + * @depends testSerializationDeserialization + * @param Patch $obj + */ + public function testGetters($obj) + { + $this->assertEquals($obj->getOp(), "TestSample"); + $this->assertEquals($obj->getPath(), "TestSample"); + $this->assertEquals($obj->getValue(), "TestSampleObject"); + $this->assertEquals($obj->getFrom(), "TestSample"); + } + + /** + * @depends testSerializationDeserialization + * @param Patch $obj + */ + public function testDeprecatedGetters($obj) + { + } + + /** + * @depends testSerializationDeserialization + * @param Patch $obj + */ + public function testDeprecatedSetterNormalGetter($obj) + { + + //Test All Deprecated Getters and Normal Getters + $this->testDeprecatedGetters($obj); + $this->testGetters($obj); + } + + + +} diff --git a/tests/PayPal/Test/Api/PresentationTest.php b/tests/PayPal/Test/Api/PresentationTest.php new file mode 100644 index 00000000..26fdbd0e --- /dev/null +++ b/tests/PayPal/Test/Api/PresentationTest.php @@ -0,0 +1,109 @@ +assertNotNull($obj); + $this->assertNotNull($obj->getBrandName()); + $this->assertNotNull($obj->getLogoImage()); + $this->assertNotNull($obj->getLocaleCode()); + $this->assertEquals(self::getJson(), $obj->toJson()); + return $obj; + } + + /** + * @depends testSerializationDeserialization + * @param Presentation $obj + */ + public function testGetters($obj) + { + $this->assertEquals($obj->getBrandName(), "TestSample"); + $this->assertEquals($obj->getLogoImage(), "TestSample"); + $this->assertEquals($obj->getLocaleCode(), "TestSample"); + } + + /** + * @depends testSerializationDeserialization + * @param Presentation $obj + */ + public function testDeprecatedGetters($obj) + { + $this->assertEquals($obj->getBrand_name(), "TestSample"); + $this->assertEquals($obj->getLogo_image(), "TestSample"); + $this->assertEquals($obj->getLocale_code(), "TestSample"); + } + + /** + * @depends testSerializationDeserialization + * @param Presentation $obj + */ + public function testDeprecatedSetterNormalGetter($obj) + { + + // Check for Brand_name + $obj->setBrandName(null); + $this->assertNull($obj->getBrand_name()); + $this->assertNull($obj->getBrandName()); + $this->assertSame($obj->getBrandName(), $obj->getBrand_name()); + $obj->setBrand_name("TestSample"); + $this->assertEquals($obj->getBrand_name(), "TestSample"); + + // Check for Logo_image + $obj->setLogoImage(null); + $this->assertNull($obj->getLogo_image()); + $this->assertNull($obj->getLogoImage()); + $this->assertSame($obj->getLogoImage(), $obj->getLogo_image()); + $obj->setLogo_image("TestSample"); + $this->assertEquals($obj->getLogo_image(), "TestSample"); + + // Check for Locale_code + $obj->setLocaleCode(null); + $this->assertNull($obj->getLocale_code()); + $this->assertNull($obj->getLocaleCode()); + $this->assertSame($obj->getLocaleCode(), $obj->getLocale_code()); + $obj->setLocale_code("TestSample"); + $this->assertEquals($obj->getLocale_code(), "TestSample"); + + //Test All Deprecated Getters and Normal Getters + $this->testDeprecatedGetters($obj); + $this->testGetters($obj); + } + + + +} diff --git a/tests/PayPal/Test/Api/WebProfileTest.php b/tests/PayPal/Test/Api/WebProfileTest.php index c88d64dc..0c0345be 100644 --- a/tests/PayPal/Test/Api/WebProfileTest.php +++ b/tests/PayPal/Test/Api/WebProfileTest.php @@ -2,6 +2,11 @@ namespace PayPal\Test\Api; +use PayPal\Common\ResourceModel; +use PayPal\Validation\ArgumentValidator; +use PayPal\Api\CreateProfileResponse; +use PayPal\Rest\ApiContext; +use PayPal\Transport\PPRestCall; use PayPal\Api\WebProfile; /** @@ -11,73 +16,219 @@ */ class WebProfileTest extends \PHPUnit_Framework_TestCase { + /** + * Gets Json String of Object WebProfile + * @return string + */ + public static function getJson() + { + return json_encode(json_decode('{"id":"TestSample","name":"TestSample","flow_config":' .FlowConfigTest::getJson() . ',"input_fields":' .InputFieldsTest::getJson() . ',"presentation":' .PresentationTest::getJson() . '}')); + } - public function testCreateprofileSerialization() + /** + * Gets Object Instance with Json data filled in + * @return WebProfile + */ + public static function getObject() { - $requestBody = '{"name":"someName2' . uniqid() . '","presentation":{"logo_image":"http://www.ebay.com"},"input_fields":{"no_shipping":1,"address_override":1},"flow_config":{"landing_page_type":"billing","bank_txn_pending_url":"http://www.ebay.com"}}'; - $requestBodyEncoded = json_encode(json_decode($requestBody, true)); - $object = new WebProfile($requestBodyEncoded); + return new WebProfile(self::getJson()); + } + - $json = $object->toJson(); - $this->assertEquals($requestBodyEncoded, $json); + /** + * Tests for Serialization and Deserialization Issues + * @return WebProfile + */ + public function testSerializationDeserialization() + { + $obj = new WebProfile(self::getJson()); + $this->assertNotNull($obj); + $this->assertNotNull($obj->getId()); + $this->assertNotNull($obj->getName()); + $this->assertNotNull($obj->getFlowConfig()); + $this->assertNotNull($obj->getInputFields()); + $this->assertNotNull($obj->getPresentation()); + $this->assertEquals(self::getJson(), $obj->toJson()); + return $obj; } + /** + * @depends testSerializationDeserialization + * @param WebProfile $obj + */ + public function testGetters($obj) + { + $this->assertEquals($obj->getId(), "TestSample"); + $this->assertEquals($obj->getName(), "TestSample"); + $this->assertEquals($obj->getFlowConfig(), FlowConfigTest::getObject()); + $this->assertEquals($obj->getInputFields(), InputFieldsTest::getObject()); + $this->assertEquals($obj->getPresentation(), PresentationTest::getObject()); + } /** - * @group integration + * @depends testSerializationDeserialization + * @param WebProfile $obj */ - public function testCreateprofileOperation() + public function testDeprecatedGetters($obj) { - $requestBody = '{"name":"someName2' . uniqid() . '","presentation":{"logo_image":"http://www.ebay.com"},"input_fields":{"no_shipping":1,"address_override":1},"flow_config":{"landing_page_type":"billing","bank_txn_pending_url":"http://www.ebay.com"}}'; - $requestBodyEncoded = json_encode(json_decode($requestBody, true)); - $object = new WebProfile($requestBodyEncoded); - $response = $object->create(null); - $this->assertNotNull($response); - return $response->getId(); + $this->assertEquals($obj->getFlow_config(), FlowConfigTest::getObject()); + $this->assertEquals($obj->getInput_fields(), InputFieldsTest::getObject()); + } + + /** + * @depends testSerializationDeserialization + * @param WebProfile $obj + */ + public function testDeprecatedSetterNormalGetter($obj) + { + + // Check for Flow_config + $obj->setFlowConfig(null); + $this->assertNull($obj->getFlow_config()); + $this->assertNull($obj->getFlowConfig()); + $this->assertSame($obj->getFlowConfig(), $obj->getFlow_config()); + $obj->setFlow_config(FlowConfigTest::getObject()); + $this->assertEquals($obj->getFlow_config(), FlowConfigTest::getObject()); + + // Check for Input_fields + $obj->setInputFields(null); + $this->assertNull($obj->getInput_fields()); + $this->assertNull($obj->getInputFields()); + $this->assertSame($obj->getInputFields(), $obj->getInput_fields()); + $obj->setInput_fields(InputFieldsTest::getObject()); + $this->assertEquals($obj->getInput_fields(), InputFieldsTest::getObject()); + + //Test All Deprecated Getters and Normal Getters + $this->testDeprecatedGetters($obj); + $this->testGetters($obj); } /** - * @depends testCreateprofileOperation - * @group integration + * @dataProvider mockProvider + * @param WebProfile $obj */ - public function testGetprofileOperation($profileId) + public function testCreate($obj, $mockApiContext) { - $response = WebProfile::get($profileId, null); - $this->assertNotNull($response); - $this->assertEquals($response->getId(), $profileId); - $this->assertEquals("http://www.ebay.com", $response->getPresentation()->getLogoImage()); - $this->assertEquals(1, $response->getInputFields()->getNoShipping()); - $this->assertEquals(1, $response->getInputFields()->getAddressOverride()); - $this->assertEquals("billing", $response->getFlowConfig()->getLandingPageType()); - $this->assertEquals("http://www.ebay.com", $response->getFlowConfig()->getBankTxnPendingUrl()); - return $response->getId(); + $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall') + ->disableOriginalConstructor() + ->getMock(); + + $mockPPRestCall->expects($this->any()) + ->method('execute') + ->will($this->returnValue( + CreateProfileResponseTest::getJson() + )); + + $result = $obj->create($mockApiContext, $mockPPRestCall); + $this->assertNotNull($result); } + /** + * @dataProvider mockProvider + * @param WebProfile $obj + */ + public function testUpdate($obj, $mockApiContext) + { + $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall') + ->disableOriginalConstructor() + ->getMock(); + $mockPPRestCall->expects($this->any()) + ->method('execute') + ->will($this->returnValue( + true + )); - public function testValidationerrorSerialization() + $result = $obj->update($mockApiContext, $mockPPRestCall); + $this->assertNotNull($result); + } + /** + * @dataProvider mockProvider + * @param WebProfile $obj + */ + public function testPartialUpdate($obj, $mockApiContext) { - $requestBody = '{"name":"sampleName' . uniqid() . '","presentation":{"logo_image":"http://www.ebay.com"},"input_fields":{"no_shipping":4,"address_override":1},"flow_config":{"landing_page_type":"billing","bank_txn_pending_url":"ht//www.ebay.com"}}'; - $requestBodyEncoded = json_encode(json_decode($requestBody, true)); - $object = new WebProfile($requestBodyEncoded); + $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall') + ->disableOriginalConstructor() + ->getMock(); + + $mockPPRestCall->expects($this->any()) + ->method('execute') + ->will($this->returnValue( + true + )); + $patch = array(PatchTest::getObject()); - $json = $object->toJson(); - $this->assertEquals($requestBodyEncoded, $json); + $result = $obj->partial_update($patch, $mockApiContext, $mockPPRestCall); + $this->assertNotNull($result); } + /** + * @dataProvider mockProvider + * @param WebProfile $obj + */ + public function testGet($obj, $mockApiContext) + { + $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall') + ->disableOriginalConstructor() + ->getMock(); + $mockPPRestCall->expects($this->any()) + ->method('execute') + ->will($this->returnValue( + WebProfileTest::getJson() + )); + $result = $obj->get("profileId", $mockApiContext, $mockPPRestCall); + $this->assertNotNull($result); + } /** - * @group integration - * @expectedException PayPal\Exception\PPConnectionException - * @expectedExceptionCode 400 + * @dataProvider mockProvider + * @param WebProfile $obj */ - public function testValidationerrorOperation() + public function testGetList($obj, $mockApiContext) { - $requestBody = '{"name":"sampleName' . uniqid() . '","presentation":{"logo_image":"http://www.ebay.com"},"input_fields":{"no_shipping":4,"address_override":1},"flow_config":{"landing_page_type":"billing","bank_txn_pending_url":"ht//www.ebay.com"}}'; - $requestBodyEncoded = json_encode(json_decode($requestBody, true)); - $object = new WebProfile($requestBodyEncoded); - $response = $object->create(null); - return $response->getId(); + $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall') + ->disableOriginalConstructor() + ->getMock(); + + $mockPPRestCall->expects($this->any()) + ->method('execute') + ->will($this->returnValue( + json_encode(array(json_decode(WebProfileTest::getJson()))) + )); + + $result = $obj->get_list($mockApiContext, $mockPPRestCall); + $this->assertNotNull($result); } + /** + * @dataProvider mockProvider + * @param WebProfile $obj + */ + public function testDelete($obj, $mockApiContext) + { + $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall') + ->disableOriginalConstructor() + ->getMock(); + $mockPPRestCall->expects($this->any()) + ->method('execute') + ->will($this->returnValue( + true + )); + + $result = $obj->delete($mockApiContext, $mockPPRestCall); + $this->assertNotNull($result); + } + + public function mockProvider() + { + $obj = self::getObject(); + $mockApiContext = $this->getMockBuilder('ApiContext') + ->disableOriginalConstructor() + ->getMock(); + return array( + array($obj, $mockApiContext), + array($obj, null) + ); + } } diff --git a/tests/PayPal/Test/Auth/Openid/PPOpenIdAddressTest.php b/tests/PayPal/Test/Auth/Openid/PPOpenIdAddressTest.php new file mode 100644 index 00000000..88752965 --- /dev/null +++ b/tests/PayPal/Test/Auth/Openid/PPOpenIdAddressTest.php @@ -0,0 +1,50 @@ +addr = self::getTestData(); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } + + public static function getTestData() + { + $addr = new PPOpenIdAddress(); + $addr->setCountry("US")->setLocality("San Jose") + ->setPostalCode("95112")->setRegion("CA") + ->setStreetAddress("1, North 1'st street"); + return $addr; + } + + /** + * @test + */ + public function testSerializationDeserialization() + { + $addrCopy = new PPOpenIdAddress(); + $addrCopy->fromJson($this->addr->toJson()); + + $this->assertEquals($this->addr, $addrCopy); + } +} diff --git a/tests/PayPal/Test/Auth/Openid/PPOpenIdErrorTest.php b/tests/PayPal/Test/Auth/Openid/PPOpenIdErrorTest.php new file mode 100644 index 00000000..635d3290 --- /dev/null +++ b/tests/PayPal/Test/Auth/Openid/PPOpenIdErrorTest.php @@ -0,0 +1,45 @@ +error = new PPOpenIdError(); + $this->error->setErrorDescription('error description') + ->setErrorUri('http://developer.paypal.com/api/error') + ->setError('VALIDATION_ERROR'); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } + + /** + * @test + */ + public function testSerializationDeserialization() + { + $errorCopy = new PPOpenIdError(); + $errorCopy->fromJson($this->error->toJson()); + + $this->assertEquals($this->error, $errorCopy); + } +} diff --git a/tests/PayPal/Test/Auth/Openid/PPOpenIdSessionTest.php b/tests/PayPal/Test/Auth/Openid/PPOpenIdSessionTest.php new file mode 100644 index 00000000..862a5323 --- /dev/null +++ b/tests/PayPal/Test/Auth/Openid/PPOpenIdSessionTest.php @@ -0,0 +1,93 @@ +context = new \PayPal\Rest\ApiContext(); + $this->context->setConfig( + array( + 'acct1.ClientId' => 'DummyId', + 'acct1.ClientSecret' => 'A8VERY8SECRET8VALUE0', + 'mode' => 'live' + ) + ); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } + + + /** + * @test + */ + public function testLoginUrlForMultipleScopes() + { + + $clientId = "AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd"; + $redirectUri = 'https://devtools-paypal.com/'; + $scope = array('this', 'that', 'and more'); + + $expectedBaseUrl = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize"; + + $this->assertEquals($expectedBaseUrl . "?client_id=$clientId&response_type=code&scope=this+that+and+more+openid&redirect_uri=" . urlencode($redirectUri), + PPOpenIdSession::getAuthorizationUrl($redirectUri, $scope, $clientId), "Failed case - custom scope"); + + $scope = array(); + $this->assertEquals($expectedBaseUrl . "?client_id=$clientId&response_type=code&scope=openid+profile+address+email+phone+" . urlencode("https://uri.paypal.com/services/paypalattributes") . "+" . urlencode('https://uri.paypal.com/services/expresscheckout') . "&redirect_uri=" . urlencode($redirectUri), + PPOpenIdSession::getAuthorizationUrl($redirectUri, $scope, $clientId), "Failed case - default scope"); + + + $scope = array('openid'); + $this->assertEquals($expectedBaseUrl . "?client_id=$clientId&response_type=code&scope=openid&redirect_uri=" . urlencode($redirectUri), + PPOpenIdSession::getAuthorizationUrl($redirectUri, $scope, $clientId), "Failed case - openid scope"); + } + + /** + * @test + */ + public function testLoginWithCustomConfig() + { + + $redirectUri = 'http://mywebsite.com'; + $scope = array('this', 'that', 'and more'); + + $expectedBaseUrl = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/authorize"; + + $this->assertEquals($expectedBaseUrl . "?client_id=DummyId&response_type=code&scope=this+that+and+more+openid&redirect_uri=" . urlencode($redirectUri), + PPOpenIdSession::getAuthorizationUrl($redirectUri, $scope, "DummyId", null, null, $this->context), "Failed case - custom config"); + } + + /** + * @test + */ + public function testLogoutWithCustomConfig() + { + + $redirectUri = 'http://mywebsite.com'; + $idToken = 'abc'; + + $expectedBaseUrl = "https://www.paypal.com/webapps/auth/protocol/openidconnect/v1/endsession"; + + $this->assertEquals($expectedBaseUrl . "?id_token=$idToken&redirect_uri=" . urlencode($redirectUri) . "&logout=true", + PPOpenIdSession::getLogoutUrl($redirectUri, $idToken, $this->context), "Failed case - custom config"); + } +} diff --git a/tests/PayPal/Test/Auth/Openid/PPOpenIdTokeninfoTest.php b/tests/PayPal/Test/Auth/Openid/PPOpenIdTokeninfoTest.php new file mode 100644 index 00000000..54e90dc0 --- /dev/null +++ b/tests/PayPal/Test/Auth/Openid/PPOpenIdTokeninfoTest.php @@ -0,0 +1,76 @@ +token = new PPOpenIdTokeninfo(); + $this->token->setAccessToken("Access token") + ->setExpiresIn(900) + ->setRefreshToken("Refresh token") + ->setIdToken("id token") + ->setScope("openid address") + ->setTokenType("Bearer"); + } + + /** + * Tears down the fixture, for example, closes a network connection. + * This method is called after a test is executed. + */ + protected function tearDown() + { + } + + /** + * @test + */ + public function testSerializationDeserialization() + { + $tokenCopy = new PPOpenIdTokeninfo(); + $tokenCopy->fromJson($this->token->toJson()); + + $this->assertEquals($this->token, $tokenCopy); + } + + /** + * @t1est + * TODO: Fix Test. This test is disabled + */ + public function t1estOperations() + { + + $clientId = 'AQkquBDf1zctJOWGKWUEtKXm6qVhueUEMvXO_-MCI4DQQ4-LWvkDLIN2fGsd'; + $clientSecret = 'ELtVxAjhT7cJimnz5-Nsx9k2reTKSVfErNQF-CmrwJgxRtylkGTKlU4RvrX'; + + $params = array( + 'code' => '', + 'redirect_uri' => 'https://devtools-paypal.com/', + 'client_id' => $clientId, + 'client_secret' => $clientSecret + ); + $accessToken = PPOpenIdTokeninfo::createFromAuthorizationCode($params); + $this->assertNotNull($accessToken); + + $params = array( + 'refresh_token' => $accessToken->getRefreshToken(), + 'client_id' => $clientId, + 'client_secret' => $clientSecret + ); + $accessToken = $accessToken->createFromRefreshToken($params); + $this->assertNotNull($accessToken); + } + +} diff --git a/tests/PayPal/Test/Auth/Openid/PPOpenIdUserinfoTest.php b/tests/PayPal/Test/Auth/Openid/PPOpenIdUserinfoTest.php new file mode 100644 index 00000000..0775177d --- /dev/null +++ b/tests/PayPal/Test/Auth/Openid/PPOpenIdUserinfoTest.php @@ -0,0 +1,60 @@ +setAccountType("PERSONAL")->setAgeRange("20-30")->setBirthday("1970-01-01") + ->setEmail("me@email.com")->setEmailVerified(true) + ->setFamilyName("Doe")->setMiddleName("A")->setGivenName("John") + ->setLocale("en-US")->setGender("male")->setName("John A Doe") + ->setPayerId("A-XZASASA")->setPhoneNumber("1-408-111-1111") + ->setPicture("http://gravatar.com/me.jpg") + ->setSub("me@email.com")->setUserId("userId") + ->setVerified(true)->setVerifiedAccount(true) + ->setZoneinfo("America/PST")->setLanguage('en_US') + ->setAddress(PPOpenIdAddressTest::getTestData()); + + $userCopy = new PPOpenIdUserinfo(); + $userCopy->fromJson($user->toJSON()); + + $this->assertEquals($user, $userCopy); + } + + /** + * @test + */ + public function testInvalidParamUserInfoCall() + { + $this->setExpectedException('PayPal\Exception\PPConnectionException'); + PPOpenIdUserinfo::getUserinfo(array('access_token' => 'accessToken')); + } +} diff --git a/tests/PayPal/Test/Common/ModelTest.php b/tests/PayPal/Test/Common/ModelTest.php index ba924cb0..7ca5f07a 100644 --- a/tests/PayPal/Test/Common/ModelTest.php +++ b/tests/PayPal/Test/Common/ModelTest.php @@ -80,7 +80,7 @@ public function testSimpleClassObjectInvalidConversion() $this->assertEquals("test", $obj->getName()); $this->assertEquals("description", $obj->getDescription()); } catch (\PHPUnit_Framework_Error_Notice $ex) { - echo $ex->getMessage(); + // No need to do anything } } diff --git a/tests/PayPal/Test/Rest/CallTest.php b/tests/PayPal/Test/Rest/CallTest.php deleted file mode 100644 index 543bd6df..00000000 --- a/tests/PayPal/Test/Rest/CallTest.php +++ /dev/null @@ -1,45 +0,0 @@ -execute('/v1/payments/echo', "POST", $data, $cred); - $this->assertEquals($data, $ret); - } - - public function testExecuteWithInvalidCredentials() - { - - $cred = new OAuthTokenCredential('test', 'dummy'); - $data = '"request":"test message"'; - - $call = new Call(); - $this->setExpectedException('\PPConnectionException'); - $ret = $call->execute('/v1/payments/echo', "POST", $data, $cred); - - } - - - public function testExecuteWithDefaultCredentials() - { - - $data = '"request":"test message"'; - - $call = new Call(); - $ret = $call->execute('/v1/payments/echo', "POST", $data); - $this->assertEquals($data, $ret); - } -} \ No newline at end of file