Updated Identity Support from SDK Core

- Moved PPModels required for Identity Support
This commit is contained in:
japatel
2014-10-14 14:15:41 -05:00
parent 0cb302326a
commit dc2ac0fd63
36 changed files with 2652 additions and 587 deletions

1
.gitignore vendored
View File

@@ -1,6 +1,7 @@
build build
.DS_Store .DS_Store
phpunit.local.xml
*.log *.log
# IDE # IDE

View File

@@ -3,7 +3,6 @@
namespace PayPal\Api; namespace PayPal\Api;
use PayPal\Common\PPModel; use PayPal\Common\PPModel;
use PayPal\Rest\ApiContext;
/** /**
* Class CreateProfileResponse * Class CreateProfileResponse

View File

@@ -3,7 +3,6 @@
namespace PayPal\Api; namespace PayPal\Api;
use PayPal\Common\PPModel; use PayPal\Common\PPModel;
use PayPal\Rest\ApiContext;
use PayPal\Validation\UrlValidator; use PayPal\Validation\UrlValidator;
/** /**
@@ -72,7 +71,7 @@ class FlowConfig extends PPModel
* *
* *
* @param string $bank_txn_pending_url * @param string $bank_txn_pending_url
* @throws InvalidArgumentException * @throws \InvalidArgumentException
* @return $this * @return $this
*/ */
public function setBankTxnPendingUrl($bank_txn_pending_url) public function setBankTxnPendingUrl($bank_txn_pending_url)

View File

@@ -3,7 +3,6 @@
namespace PayPal\Api; namespace PayPal\Api;
use PayPal\Common\PPModel; use PayPal\Common\PPModel;
use PayPal\Rest\ApiContext;
/** /**
* Class InputFields * Class InputFields

View File

@@ -1,32 +1,19 @@
<?php <?php
namespace PayPal\Api; namespace PayPal\Api;
use PayPal\Common\PPModel; use PayPal\Common\ResourceModel;
use PayPal\Rest\ApiContext;
use PayPal\Rest\IResource;
use PayPal\Api\Invoices; use PayPal\Api\Invoices;
use PayPal\Transport\PPRestCall;
use PayPal\Validation\ArgumentValidator; use PayPal\Validation\ArgumentValidator;
use PayPal\Rest\ApiContext;
use PayPal\Transport\PPRestCall;
/** /**
* Class Invoice * Class Invoice
* *
* @package PayPal\Api * @package PayPal\Api
*/ */
class Invoice extends PPModel implements IResource class Invoice extends ResourceModel
{ {
private static $credential;
/**
*
* @deprecated. Pass ApiContext to create/get methods instead
*/
public static function setCredential($credential)
{
self::$credential = $credential;
}
/** /**
* Unique invoice resource identifier. * Unique invoice resource identifier.
* *
@@ -845,241 +832,250 @@ class Invoice extends PPModel implements IResource
} }
/* /**
* Creates a new invoice Resource. * Creates a new invoice Resource.
* *
* @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 * @return Invoice
*/ */
public function create($apiContext = null) public function create($apiContext = null, $restCall = null)
{ {
$payLoad = $this->toJSON(); $payLoad = $this->toJSON();
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices", "POST", $payLoad); $apiContext,
$restCall
);
$this->fromJson($json); $this->fromJson($json);
return $this; return $this;
} }
/* /**
* Search for invoice resources. * Search for invoice resources.
* *
* @param Search $search * @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 * @return Invoices
*/ */
public function search($search, $apiContext = null) public function search($search, $apiContext = null, $restCall = null)
{ {
ArgumentValidator::validate($search, 'search'); ArgumentValidator::validate($search, 'search');
$payLoad = $search->toJSON(); $payLoad = $search->toJSON();
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/search",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/search", "POST", $payLoad); $apiContext,
$restCall
);
$ret = new Invoices(); $ret = new Invoices();
$ret->fromJson($json); $ret->fromJson($json);
return $ret; return $ret;
} }
/* /**
* Sends a legitimate invoice to the payer. * 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. * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials.
* @return void * @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) { ArgumentValidator::validate($this->getId(), "Id");
throw new \InvalidArgumentException("Id cannot be null");
}
$payLoad = ""; $payLoad = "";
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/{$this->getId()}/send",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/send", "POST", $payLoad); $apiContext,
$restCall
);
return true; return true;
} }
/* /**
* Reminds the payer to pay the invoice. * Reminds the payer to pay the invoice.
* *
* @param Notification $notification * @param Notification $notification
* @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.
* @return void * @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) { ArgumentValidator::validate($this->getId(), "Id");
throw new \InvalidArgumentException("Id cannot be null"); ArgumentValidator::validate($notification, "Notification");
}
if (($notification == null)) {
throw new \InvalidArgumentException("notification cannot be null or empty");
}
$payLoad = $notification->toJSON(); $payLoad = $notification->toJSON();
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/{$this->getId()}/remind",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/remind", "POST", $payLoad); $apiContext,
$restCall
);
return true; return true;
} }
/* /**
* Cancels an invoice. * Cancels an invoice.
* *
* @param CancelNotification $cancelNotification * @param CancelNotification $cancelNotification
* @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.
* @return void * @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) { ArgumentValidator::validate($this->getId(), "Id");
throw new \InvalidArgumentException("Id cannot be null"); ArgumentValidator::validate($cancelNotification, "CancelNotification");
}
if (($cancelNotification == null)) {
throw new \InvalidArgumentException("cancelNotification cannot be null or empty");
}
$payLoad = $cancelNotification->toJSON(); $payLoad = $cancelNotification->toJSON();
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/{$this->getId()}/cancel",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/cancel", "POST", $payLoad); $apiContext,
$restCall
);
return true; return true;
} }
/* /**
* Mark the status of the invoice as paid. * Mark the status of the invoice as paid.
* *
* @param PaymentDetail $paymentDetail * @param PaymentDetail $paymentDetail
* @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.
* @return void * @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) { ArgumentValidator::validate($this->getId(), "Id");
throw new \InvalidArgumentException("Id cannot be null"); ArgumentValidator::validate($paymentDetail, "PaymentDetail");
}
if (($paymentDetail == null)) {
throw new \InvalidArgumentException("paymentDetail cannot be null or empty");
}
$payLoad = $paymentDetail->toJSON(); $payLoad = $paymentDetail->toJSON();
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/{$this->getId()}/record-payment",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/record-payment", "POST", $payLoad); $apiContext,
$restCall
);
return true; return true;
} }
/* /**
* Mark the status of the invoice as refunded. * Mark the status of the invoice as refunded.
* *
* @param RefundDetail $refundDetail * @param RefundDetail $refundDetail
* @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.
* @return void * @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) { ArgumentValidator::validate($this->getId(), "Id");
throw new \InvalidArgumentException("Id cannot be null"); ArgumentValidator::validate($refundDetail, "RefundDetail");
}
if (($refundDetail == null)) {
throw new \InvalidArgumentException("refundDetail cannot be null or empty");
}
$payLoad = $refundDetail->toJSON(); $payLoad = $refundDetail->toJSON();
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/{$this->getId()}/record-refund",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}/record-refund", "POST", $payLoad); $apiContext,
$restCall
);
return true; return true;
} }
/* /**
* Get the invoice resource for the given identifier. * Get the invoice resource for the given identifier.
* *
* @param string $invoiceId * @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 * @return Invoice
*/ */
public static function get($invoiceId, $apiContext = null) public static function get($invoiceId, $apiContext = null, $restCall = null)
{ {
if (($invoiceId == null) || (strlen($invoiceId) <= 0)) { ArgumentValidator::validate($invoiceId);
throw new \InvalidArgumentException("invoiceId cannot be null or empty");
}
$payLoad = ""; $payLoad = "";
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/$invoiceId",
} "GET",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/$invoiceId", "GET", $payLoad); $apiContext,
$restCall
);
$ret = new Invoice(); $ret = new Invoice();
$ret->fromJson($json); $ret->fromJson($json);
return $ret; return $ret;
} }
/* /**
* Get all invoices of a merchant. * 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 * @return Invoices
*/ */
public static function get_all($apiContext = null) public static function get_all($apiContext = null, $restCall = null)
{ {
$payLoad = ""; $payLoad = "";
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/",
} "GET",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/", "GET", $payLoad); $apiContext,
$restCall
);
$ret = new Invoices(); $ret = new Invoices();
$ret->fromJson($json); $ret->fromJson($json);
return $ret; return $ret;
} }
/* /**
* Full update of the invoice resource for the given identifier. * 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 * @return Invoice
*/ */
public function update($apiContext = null) public function update($apiContext = null, $restCall = null)
{ {
if ($this->getId() == null) { ArgumentValidator::validate($this->getId(), "Id");
throw new \InvalidArgumentException("Id cannot be null");
}
$payLoad = $this->toJSON(); $payLoad = $this->toJSON();
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/{$this->getId()}",
} "PUT",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}", "PUT", $payLoad); $apiContext,
$restCall
);
$this->fromJson($json); $this->fromJson($json);
return $this; return $this;
} }
/* /**
* Delete invoice resource for the given identifier. * 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. * @param ApiContext $apiContext is the APIContext for this call. It can be used to pass dynamic configuration and credentials.
* @return void * @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) { ArgumentValidator::validate($this->getId(), "Id");
throw new \InvalidArgumentException("Id cannot be null");
}
$payLoad = ""; $payLoad = "";
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/invoicing/invoices/{$this->getId()}",
} "DELETE",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/invoicing/invoices/{$this->getId()}", "DELETE", $payLoad); $apiContext,
$restCall
);
return true; return true;
} }
} }

View File

@@ -3,7 +3,6 @@
namespace PayPal\Api; namespace PayPal\Api;
use PayPal\Common\PPModel; use PayPal\Common\PPModel;
use PayPal\Rest\ApiContext;
/** /**
* Class Patch * Class Patch
@@ -14,7 +13,7 @@ use PayPal\Rest\ApiContext;
* *
* @property string op * @property string op
* @property string path * @property string path
* @property \PayPal\Api\object value * @property mixed value
* @property string from * @property string from
*/ */
class Patch extends PPModel class Patch extends PPModel
@@ -71,7 +70,7 @@ class Patch extends PPModel
* New value to apply based on the operation. op=remove does not require value. * New value to apply based on the operation. op=remove does not require value.
* *
* *
* @param \PayPal\Api\object $value * @param mixed $value
* *
* @return $this * @return $this
*/ */
@@ -84,7 +83,7 @@ class Patch extends PPModel
/** /**
* New value to apply based on the operation. op=remove does not require value. * New value to apply based on the operation. op=remove does not require value.
* *
* @return \PayPal\Api\object * @return mixed
*/ */
public function getValue() public function getValue()
{ {

View File

@@ -3,7 +3,6 @@
namespace PayPal\Api; namespace PayPal\Api;
use PayPal\Common\PPModel; use PayPal\Common\PPModel;
use PayPal\Rest\ApiContext;
/** /**
* Class Presentation * Class Presentation

View File

@@ -2,12 +2,11 @@
namespace PayPal\Api; namespace PayPal\Api;
use PayPal\Common\PPModel; use PayPal\Common\ResourceModel;
use PayPal\Rest\ApiContext;
use PayPal\Rest\IResource;
use PayPal\Api\CreateProfileResponse;
use PayPal\Transport\PPRestCall;
use PayPal\Validation\ArgumentValidator; use PayPal\Validation\ArgumentValidator;
use PayPal\Api\CreateProfileResponse;
use PayPal\Rest\ApiContext;
use PayPal\Transport\PPRestCall;
/** /**
* Class WebProfile * Class WebProfile
@@ -22,26 +21,8 @@ use PayPal\Validation\ArgumentValidator;
* @property \PayPal\Api\InputFields input_fields * @property \PayPal\Api\InputFields input_fields
* @property \PayPal\Api\Presentation presentation * @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. * ID of the web experience profile.
* *
@@ -215,17 +196,21 @@ class WebProfile extends PPModel implements IResource
/** /**
* Create a web experience profile by passing the name of the profile and other profile details in the request JSON to the request URI. * 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 * @return CreateProfileResponse
*/ */
public function create($apiContext = null) public function create($apiContext = null, $restCall = null)
{ {
$payLoad = $this->toJSON(); $payLoad = $this->toJSON();
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/payment-experience/web-profiles/",
} "POST",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/", "POST", $payLoad); null,
$apiContext,
$restCall
);
$ret = new CreateProfileResponse(); $ret = new CreateProfileResponse();
$ret->fromJson($json); $ret->fromJson($json);
return $ret; return $ret;
@@ -234,18 +219,22 @@ class WebProfile extends PPModel implements IResource
/** /**
* 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. * 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 * @return bool
*/ */
public function update($apiContext = null) public function update($apiContext = null, $restCall = null)
{ {
ArgumentValidator::validate($this->getId(), "Id"); ArgumentValidator::validate($this->getId(), "Id");
$payLoad = $this->toJSON(); $payLoad = $this->toJSON();
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/payment-experience/web-profiles/{$this->getId()}",
} "PUT",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/{$this->getId()}", "PUT", $payLoad); null,
$apiContext,
$restCall
);
return true; return true;
} }
@@ -253,23 +242,27 @@ class WebProfile extends PPModel implements IResource
* 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. * 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 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 * @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($this->getId(), "Id");
ArgumentValidator::validate($patch, 'patch'); ArgumentValidator::validate($patch, 'patch');
$payload = array();
foreach ($patch as $patchObject) { foreach ($patch as $patchObject) {
$payload[] = $patchObject->toArray(); $payload[] = $patchObject->toArray();
} }
$payLoad = json_encode($payload); $payLoad = json_encode($payload);
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/payment-experience/web-profiles/{$this->getId()}",
} "PATCH",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/{$this->getId()}", "PATCH", $payLoad); null,
$apiContext,
$restCall
);
return true; return true;
} }
@@ -277,18 +270,22 @@ class WebProfile extends PPModel implements IResource
* Retrieve the details of a particular web experience profile by passing the ID of the profile to the request URI. * Retrieve the details of a particular web experience profile by passing the ID of the profile to the request URI.
* *
* @param string $profileId * @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 * @return WebProfile
*/ */
public static function get($profileId, $apiContext = null) public static function get($profileId, $apiContext = null, $restCall = null)
{ {
ArgumentValidator::validate($profileId, 'profileId'); ArgumentValidator::validate($profileId, 'profileId');
$payLoad = ""; $payLoad = "";
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/payment-experience/web-profiles/$profileId",
} "GET",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/$profileId", "GET", $payLoad); null,
$apiContext,
$restCall
);
$ret = new WebProfile(); $ret = new WebProfile();
$ret->fromJson($json); $ret->fromJson($json);
return $ret; return $ret;
@@ -297,35 +294,43 @@ class WebProfile extends PPModel implements IResource
/** /**
* Lists all web experience profiles that exist for a merchant (or subject). * 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[] * @return WebProfile[]
*/ */
public static function get_list($apiContext = null) public static function get_list($apiContext = null, $restCall = null)
{ {
$payLoad = ""; $payLoad = "";
if ($apiContext == null) { $json = self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/payment-experience/web-profiles/",
} "GET",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/", "GET", $payLoad); null,
$apiContext,
$restCall
);
return WebProfile::getList($json); return WebProfile::getList($json);
} }
/** /**
* Delete an existing web experience profile by passing the profile ID to the request URI. * 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 * @return bool
*/ */
public function delete($apiContext = null) public function delete($apiContext = null, $restCall = null)
{ {
ArgumentValidator::validate($this->getId(), "Id"); ArgumentValidator::validate($this->getId(), "Id");
$payLoad = ""; $payLoad = "";
if ($apiContext == null) { self::executeCall(
$apiContext = new ApiContext(self::$credential); "/v1/payment-experience/web-profiles/{$this->getId()}",
} "DELETE",
$call = new PPRestCall($apiContext); $payLoad,
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/payment-experience/web-profiles/{$this->getId()}", "DELETE", $payLoad); null,
$apiContext,
$restCall
);
return true; return true;
} }

View File

@@ -0,0 +1,119 @@
<?php
namespace PayPal\Auth\Openid;
use PayPal\Common\PPModel;
/**
* End-User's preferred address.
*/
class PPOpenIdAddress extends PPModel
{
/**
* Full street address component, which may include house number, street name.
*
* @param string $street_address
*/
public function setStreetAddress($street_address)
{
$this->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;
}
}

View File

@@ -0,0 +1,76 @@
<?php
namespace PayPal\Auth\Openid;
use PayPal\Common\PPModel;
/**
* Error resource
*/
class PPOpenIdError extends PPModel
{
/**
* A single ASCII error code from the following enum.
*
* @param string $error
*/
public function setError($error)
{
$this->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;
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace PayPal\Auth\Openid;
use PayPal\Core\PPConstants;
use PayPal\Rest\ApiContext;
class PPOpenIdSession
{
/**
* Returns the PayPal URL to which the user must be redirected to
* start the authentication / authorization process.
*
* @param string $redirectUri Uri on merchant website to where
* the user must be redirected to post paypal login
* @param array $scope The access privilges that you are requesting for
* from the user. Pass empty array for all scopes.
* @param string $clientId client id from developer portal
* See https://developer.paypal.com/webapps/developer/docs/integration/direct/log-in-with-paypal/detailed/#attributes for more
* @param ApiContext $apiContext Optional API Context
*/
public static function getAuthorizationUrl($redirectUri, $scope, $clientId, $nonce = null, $state = null, $apiContext = null)
{
$apiContext = $apiContext ? $apiContext : new ApiContext();
$config = $apiContext->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;
}
}

View File

@@ -0,0 +1,230 @@
<?php
namespace PayPal\Auth\Openid;
use PayPal\Common\ResourceModel;
use PayPal\Rest\ApiContext;
use PayPal\Transport\PPRestCall;
/**
* Token grant resource
*/
class PPOpenIdTokeninfo extends ResourceModel
{
/**
* OPTIONAL, if identical to the scope requested by the client; otherwise, REQUIRED.
*
* @param string $scope
*/
public function setScope($scope)
{
$this->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;
}
}

View File

@@ -0,0 +1,491 @@
<?php
namespace PayPal\Auth\Openid;
use PayPal\Common\ResourceModel;
use PayPal\Rest\ApiContext;
/**
* OpenIdConnect UserInfo Resource
*/
class PPOpenIdUserinfo extends ResourceModel
{
/**
* Subject - Identifier for the End-User at the Issuer.
*
* @param string $user_id
*/
public function setUserId($user_id)
{
$this->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;
}
}

View File

@@ -158,7 +158,7 @@ class PPModel
/** @var self $o */ /** @var self $o */
$o = new $clazz(); $o = new $clazz();
$o->fromArray($v); $o->fromArray($v);
$this->setValue($k, $o); $this->assignValue($k, $o);
} else { } else {
$arr = array(); $arr = array();
foreach ($v as $nk => $nv) { foreach ($v as $nk => $nv) {
@@ -170,7 +170,7 @@ class PPModel
$arr[$nk] = $nv; $arr[$nk] = $nv;
} }
} }
$this->setValue($k, $arr); $this->assignValue($k, $arr);
} }
} else { } else {
$this->$k = $v; $this->$k = $v;
@@ -179,7 +179,7 @@ class PPModel
return $this; return $this;
} }
private function setValue($key, $value) private function assignValue($key, $value)
{ {
if (ModelAccessorValidator::validate($this, $this->convertToCamelCase($key))) { if (ModelAccessorValidator::validate($this, $this->convertToCamelCase($key))) {
$setter = "set" . $this->convertToCamelCase($key); $setter = "set" . $this->convertToCamelCase($key);

View File

@@ -0,0 +1,60 @@
<?php
namespace PayPal\Common;
use PayPal\Handler\IPPHandler;
use PayPal\Rest\ApiContext;
use PayPal\Rest\IResource;
use PayPal\Transport\PPRestCall;
/**
* Class ResourceModel
* An Executable PPModel Class
*
* @package PayPal\Common
*/
class ResourceModel extends PPModel implements IResource
{
/**
* 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;
}
/**
* Execute SDK Call to Paypal services
*
* @param string $url
* @param string $method
* @param string $payLoad
* @param array $headers
* @param ApiContext $apiContext
* @param PPRestCall $restCall
* @param array $handlers
* @return string json response of the object
*/
protected static function executeCall($url, $method, $payLoad, $headers = array(), $apiContext = null, $restCall = null, $handlers = array('PayPal\Rest\RestHandler'))
{
//Initialize the context and rest call object if not provided explicitly
$apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
$restCall = $restCall ? $restCall : new PPRestCall($apiContext);
//Make the execution call
$json = $restCall->execute($handlers, $url, $method, $payLoad, $headers);
return $json;
}
}

View File

@@ -15,5 +15,8 @@ class PPConstants
const SDK_VERSION = '0.11.0'; const SDK_VERSION = '0.11.0';
const REST_SANDBOX_ENDPOINT = "https://api.sandbox.paypal.com/"; 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 REST_LIVE_ENDPOINT = "https://api.paypal.com/";
const OPENID_REDIRECT_LIVE_URL = "https://www.paypal.com/webapps/auth/protocol/openidconnect";
} }

View File

@@ -1,130 +1,131 @@
<?php <?php
namespace PayPal\Rest; namespace PayPal\Rest;
use PayPal\Core\PPConfigManager; use PayPal\Core\PPConfigManager;
use PayPal\Core\PPCredentialManager; use PayPal\Core\PPCredentialManager;
/** /**
* Class ApiContext * Class ApiContext
* *
* Call level parameters such as request id, credentials etc * Call level parameters such as request id, credentials etc
* *
* @package PayPal\Rest * @package PayPal\Rest
*/ */
class ApiContext class ApiContext
{ {
/** /**
* Unique request id to be used for this call * Unique request id to be used for this call
* The user can either generate one as per application * The user can either generate one as per application
* needs or let the SDK generate one * needs or let the SDK generate one
* *
* @var null|string $requestId * @var null|string $requestId
*/ */
private $requestId; private $requestId;
/** /**
* This is a placeholder for holding credential for the request * This is a placeholder for holding credential for the request
* If the value is not set, it would get the value from @\PayPal\Core\PPCredentialManager * If the value is not set, it would get the value from @\PayPal\Core\PPCredentialManager
* *
* @var \Paypal\Auth\OAuthTokenCredential * @var \Paypal\Auth\OAuthTokenCredential
*/ */
private $credential; private $credential;
/** /**
* Get Credential * Get Credential
* *
* @return \PayPal\Auth\OAuthTokenCredential * @return \PayPal\Auth\OAuthTokenCredential
*/ */
public function getCredential() public function getCredential()
{ {
if ($this->credential == null) { if ($this->credential == null) {
return PPCredentialManager::getInstance()->getCredentialObject(); return PPCredentialManager::getInstance()->getCredentialObject();
} }
return $this->credential; return $this->credential;
} }
/** /**
* Get Request ID * Get Request ID
* *
* @return string * @return string
*/ */
public function getrequestId() public function getrequestId()
{ {
if ($this->requestId == null) { if ($this->requestId == null) {
$this->requestId = $this->generateRequestId(); $this->requestId = $this->generateRequestId();
} }
return $this->requestId; return $this->requestId;
} }
/** /**
* Construct * Construct
* *
* @param \PayPal\Auth\OAuthTokenCredential $credential * @param \PayPal\Auth\OAuthTokenCredential $credential
* @param string|null $requestId * @param string|null $requestId
*/ */
public function __construct($credential = null, $requestId = null) public function __construct($credential = null, $requestId = null)
{ {
$this->requestId = $requestId; $this->requestId = $requestId;
$this->credential = $credential; $this->credential = $credential;
} }
/** /**
* Sets Config * Sets Config
* *
* @param array $config SDK configuration parameters * @param array $config SDK configuration parameters
*/ */
public function setConfig(array $config) public function setConfig(array $config)
{ {
PPConfigManager::getInstance()->addConfigs($config); PPConfigManager::getInstance()->addConfigs($config);
} }
/** /**
* Gets Configurations * Gets Configurations
* *
* @return array * @return array
*/ */
public function getConfig() public function getConfig()
{ {
return PPConfigManager::getInstance()->getConfigHashmap(); return PPConfigManager::getInstance()->getConfigHashmap();
} }
/** /**
* Gets a specific configuration from key * Gets a specific configuration from key
* *
* @param $searchKey * @param $searchKey
*/ * @return mixed
public function get($searchKey) */
{ public function get($searchKey)
PPConfigManager::getInstance()->get($searchKey); {
} return PPConfigManager::getInstance()->get($searchKey);
}
/**
* Generates a unique per request id that /**
* can be used to set the PayPal-Request-Id header * Generates a unique per request id that
* that is used for idempotency * can be used to set the PayPal-Request-Id header
* * that is used for idempotency
* @return string *
*/ * @return string
private function generateRequestId() */
{ private function generateRequestId()
static $pid = -1; {
static $addr = -1; static $pid = -1;
static $addr = -1;
if ($pid == -1) {
$pid = getmypid(); if ($pid == -1) {
} $pid = getmypid();
}
if ($addr == -1) {
if (array_key_exists('SERVER_ADDR', $_SERVER)) { if ($addr == -1) {
$addr = ip2long($_SERVER['SERVER_ADDR']); if (array_key_exists('SERVER_ADDR', $_SERVER)) {
} else { $addr = ip2long($_SERVER['SERVER_ADDR']);
$addr = php_uname('n'); } else {
} $addr = php_uname('n');
} }
}
return $addr . $pid . $_SERVER['REQUEST_TIME'] . mt_rand(0, 0xffff);
} return $addr . $pid . $_SERVER['REQUEST_TIME'] . mt_rand(0, 0xffff);
} }
}

View File

@@ -1,132 +1,132 @@
<?php <?php
/** /**
* API handler for all REST API calls * API handler for all REST API calls
*/ */
namespace PayPal\Rest; namespace PayPal\Rest;
use PayPal\Auth\OAuthTokenCredential; use PayPal\Auth\OAuthTokenCredential;
use PayPal\Common\PPUserAgent; use PayPal\Common\PPUserAgent;
use PayPal\Core\PPConstants; use PayPal\Core\PPConstants;
use PayPal\Core\PPCredentialManager; use PayPal\Core\PPCredentialManager;
use PayPal\Exception\PPConfigurationException; use PayPal\Exception\PPConfigurationException;
use PayPal\Exception\PPInvalidCredentialException; use PayPal\Exception\PPInvalidCredentialException;
use PayPal\Exception\PPMissingCredentialException; use PayPal\Exception\PPMissingCredentialException;
use PayPal\Handler\IPPHandler; use PayPal\Handler\IPPHandler;
/** /**
* Class RestHandler * Class RestHandler
*/ */
class RestHandler implements IPPHandler class RestHandler implements IPPHandler
{ {
/** /**
* Private Variable * Private Variable
* *
* @var \Paypal\Rest\ApiContext $apiContext * @var \Paypal\Rest\ApiContext $apiContext
*/ */
private $apiContext; private $apiContext;
/** /**
* Public Variable * Public Variable
* *
* @var string $sdkName * @var string $sdkName
*/ */
public static $sdkName = "rest-sdk-php"; public static $sdkName = "rest-sdk-php";
/** /**
* Public Variable * Public Variable
* *
* @var string $sdkVersion * @var string $sdkVersion
*/ */
public static $sdkVersion = "0.6.0"; public static $sdkVersion = "0.6.0";
/** /**
* Construct * Construct
* *
* @param \Paypal\Rest\ApiContext $apiContext * @param \Paypal\Rest\ApiContext $apiContext
*/ */
public function __construct($apiContext) public function __construct($apiContext)
{ {
$this->apiContext = $apiContext; $this->apiContext = $apiContext;
} }
/** /**
* @param \Paypal\Core\PPHttpConfig $httpConfig * @param \Paypal\Core\PPHttpConfig $httpConfig
* @param string $request * @param string $request
* @param mixed $options * @param mixed $options
* @return mixed|void * @return mixed|void
* @throws PPConfigurationException * @throws PPConfigurationException
* @throws PPInvalidCredentialException * @throws PPInvalidCredentialException
* @throws PPMissingCredentialException * @throws PPMissingCredentialException
*/ */
public function handle($httpConfig, $request, $options) public function handle($httpConfig, $request, $options)
{ {
$credential = $this->apiContext->getCredential(); $credential = $this->apiContext->getCredential();
$config = $this->apiContext->getConfig(); $config = $this->apiContext->getConfig();
if ($credential == null) { if ($credential == null) {
// Try picking credentials from the config file // Try picking credentials from the config file
$credMgr = PPCredentialManager::getInstance($config); $credMgr = PPCredentialManager::getInstance($config);
$credValues = $credMgr->getCredentialObject(); $credValues = $credMgr->getCredentialObject();
if (!is_array($credValues)) { if (!is_array($credValues)) {
throw new PPMissingCredentialException("Empty or invalid credentials passed"); throw new PPMissingCredentialException("Empty or invalid credentials passed");
} }
$credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']); $credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']);
} }
if ($credential == null || !($credential instanceof OAuthTokenCredential)) { if ($credential == null || !($credential instanceof OAuthTokenCredential)) {
throw new PPInvalidCredentialException("Invalid credentials passed"); throw new PPInvalidCredentialException("Invalid credentials passed");
} }
$httpConfig->setUrl( $httpConfig->setUrl(
rtrim(trim($this->_getEndpoint($config)), '/') . rtrim(trim($this->_getEndpoint($config)), '/') .
(isset($options['path']) ? $options['path'] : '') (isset($options['path']) ? $options['path'] : '')
); );
if (!array_key_exists("User-Agent", $httpConfig->getHeaders())) { if (!array_key_exists("User-Agent", $httpConfig->getHeaders())) {
$httpConfig->addHeader("User-Agent", PPUserAgent::getValue(self::$sdkName, self::$sdkVersion)); $httpConfig->addHeader("User-Agent", PPUserAgent::getValue(self::$sdkName, self::$sdkVersion));
} }
if (!is_null($credential) && $credential instanceof OAuthTokenCredential) { if (!is_null($credential) && $credential instanceof OAuthTokenCredential && is_null($httpConfig->getHeader('Authorization'))) {
$httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config)); $httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config), false);
} }
if ($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') { if ($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') {
$httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId()); $httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId());
} }
} }
/** /**
* End Point * End Point
* *
* @param array $config * @param array $config
* *
* @return string * @return string
* @throws \PayPal\Exception\PPConfigurationException * @throws \PayPal\Exception\PPConfigurationException
*/ */
private function _getEndpoint($config) private function _getEndpoint($config)
{ {
if (isset($config['service.EndPoint'])) { if (isset($config['service.EndPoint'])) {
return $config['service.EndPoint']; return $config['service.EndPoint'];
} else if (isset($config['mode'])) { } else if (isset($config['mode'])) {
switch (strtoupper($config['mode'])) { switch (strtoupper($config['mode'])) {
case 'SANDBOX': case 'SANDBOX':
return PPConstants::REST_SANDBOX_ENDPOINT; return PPConstants::REST_SANDBOX_ENDPOINT;
break; break;
case 'LIVE': case 'LIVE':
return PPConstants::REST_LIVE_ENDPOINT; return PPConstants::REST_LIVE_ENDPOINT;
break; break;
default: default:
throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live'); throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live');
break; break;
} }
} else { } else {
throw new PPConfigurationException( throw new PPConfigurationException(
'You must set one of service.endpoint or mode parameters in your configuration' 'You must set one of service.endpoint or mode parameters in your configuration'
); );
} }
} }
} }

View File

@@ -4,6 +4,7 @@ namespace PayPal\Transport;
use PayPal\Core\PPLoggingManager; use PayPal\Core\PPLoggingManager;
use PayPal\Core\PPHttpConfig; use PayPal\Core\PPHttpConfig;
use PayPal\Core\PPHttpConnection; use PayPal\Core\PPHttpConnection;
use PayPal\Rest\ApiContext;
/** /**
* Class PPRestCall * Class PPRestCall
@@ -24,7 +25,7 @@ class PPRestCall
/** /**
* API Context * API Context
* *
* @var \Paypal\Rest\ApiContext * @var ApiContext
*/ */
private $apiContext; private $apiContext;
@@ -32,9 +33,9 @@ class PPRestCall
/** /**
* Default Constructor * 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->apiContext = $apiContext;
$this->logger = PPLoggingManager::getInstance(__CLASS__); $this->logger = PPLoggingManager::getInstance(__CLASS__);
@@ -54,6 +55,7 @@ class PPRestCall
$config = $this->apiContext->getConfig(); $config = $this->apiContext->getConfig();
$httpConfig = new PPHttpConfig(null, $method); $httpConfig = new PPHttpConfig(null, $method);
$headers = $headers ? $headers : array();
$httpConfig->setHeaders($headers + $httpConfig->setHeaders($headers +
array( array(
'Content-Type' => 'application/json' 'Content-Type' => 'application/json'

View File

@@ -9,6 +9,10 @@
convertWarningsToExceptions="true" convertWarningsToExceptions="true"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"> testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader">
<php>
<env name="REST_MODE" value="sandbox"/>
</php>
<testsuites> <testsuites>
<testsuite name="All"> <testsuite name="All">
<directory>tests</directory> <directory>tests</directory>
@@ -29,4 +33,4 @@
</exclude> </exclude>
</whitelist> </whitelist>
</filter> </filter>
</phpunit> </phpunit>

View File

@@ -1,6 +1,10 @@
PayPal PHP SDK release notes PayPal PHP SDK release notes
============================ ============================
v0.13.1
----
* Updated Identity Support from SDK Core
v0.13.0 v0.13.0
---- ----
* Enabled Payment Experience * Enabled Payment Experience

View File

@@ -0,0 +1,23 @@
<?php
require __DIR__ . '/../bootstrap.php';
$clientId = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS';
$clientSecret = 'EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL';
$baseUrl = getBaseUrl() . '/ExecuteAuth.php?success=true';
//Get User Consent
$redirectUrl = \PayPal\Auth\Openid\PPOpenIdSession::getAuthorizationUrl(
$baseUrl,
array('profile', 'email', 'phone'),
$clientId,
null,
null,
$apiContext
);
header("Location: $redirectUrl");
exit;

View File

@@ -0,0 +1,39 @@
<?php
// #Execute Payment Sample
// This sample shows how you can complete
// a payment that has been approved by
// the buyer by logging into paypal site.
// You can optionally update transaction
// information by passing in one or more transactions.
// API used: POST '/v1/payments/payment/<payment-id>/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);
}

View File

@@ -0,0 +1,78 @@
<?php
namespace PayPal\Test\Api;
use PayPal\Common\PPModel;
use PayPal\Api\CreateProfileResponse;
/**
* Class CreateProfileResponse
*
* @package PayPal\Test\Api
*/
class CreateProfileResponseTest extends \PHPUnit_Framework_TestCase
{
/**
* Gets Json String of Object CreateProfileResponse
* @return string
*/
public static function getJson()
{
return json_encode(json_decode('{"id":"TestSample"}'));
}
/**
* Gets Object Instance with Json data filled in
* @return CreateProfileResponse
*/
public static function getObject()
{
return new CreateProfileResponse(self::getJson());
}
/**
* Tests for Serialization and Deserialization Issues
* @return CreateProfileResponse
*/
public function testSerializationDeserialization()
{
$obj = new CreateProfileResponse(self::getJson());
$this->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);
}
}

View File

@@ -0,0 +1,105 @@
<?php
namespace PayPal\Test\Api;
use PayPal\Common\PPModel;
use PayPal\Api\FlowConfig;
/**
* Class FlowConfig
*
* @package PayPal\Test\Api
*/
class FlowConfigTest extends \PHPUnit_Framework_TestCase
{
/**
* Gets Json String of Object FlowConfig
* @return string
*/
public static function getJson()
{
return json_encode(json_decode('{"landing_page_type":"TestSample","bank_txn_pending_url":"http://www.google.com"}'));
}
/**
* Gets Object Instance with Json data filled in
* @return FlowConfig
*/
public static function getObject()
{
return new FlowConfig(self::getJson());
}
/**
* Tests for Serialization and Deserialization Issues
* @return FlowConfig
*/
public function testSerializationDeserialization()
{
$obj = new FlowConfig(self::getJson());
$this->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());
}
}

View File

@@ -0,0 +1,109 @@
<?php
namespace PayPal\Test\Api;
use PayPal\Common\PPModel;
use PayPal\Api\InputFields;
/**
* Class InputFields
*
* @package PayPal\Test\Api
*/
class InputFieldsTest extends \PHPUnit_Framework_TestCase
{
/**
* Gets Json String of Object InputFields
* @return string
*/
public static function getJson()
{
return json_encode(json_decode('{"allow_note":true,"no_shipping":123,"address_override":123}'));
}
/**
* Gets Object Instance with Json data filled in
* @return InputFields
*/
public static function getObject()
{
return new InputFields(self::getJson());
}
/**
* Tests for Serialization and Deserialization Issues
* @return InputFields
*/
public function testSerializationDeserialization()
{
$obj = new InputFields(self::getJson());
$this->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);
}
}

View File

@@ -0,0 +1,84 @@
<?php
namespace PayPal\Test\Api;
use PayPal\Common\PPModel;
use PayPal\Api\Patch;
/**
* Class Patch
*
* @package PayPal\Test\Api
*/
class PatchTest extends \PHPUnit_Framework_TestCase
{
/**
* Gets Json String of Object Patch
* @return string
*/
public static function getJson()
{
return json_encode(json_decode('{"op":"TestSample","path":"TestSample","value":"TestSampleObject","from":"TestSample"}'));
}
/**
* Gets Object Instance with Json data filled in
* @return Patch
*/
public static function getObject()
{
return new Patch(self::getJson());
}
/**
* Tests for Serialization and Deserialization Issues
* @return Patch
*/
public function testSerializationDeserialization()
{
$obj = new Patch(self::getJson());
$this->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);
}
}

View File

@@ -0,0 +1,109 @@
<?php
namespace PayPal\Test\Api;
use PayPal\Common\PPModel;
use PayPal\Api\Presentation;
/**
* Class Presentation
*
* @package PayPal\Test\Api
*/
class PresentationTest extends \PHPUnit_Framework_TestCase
{
/**
* Gets Json String of Object Presentation
* @return string
*/
public static function getJson()
{
return json_encode(json_decode('{"brand_name":"TestSample","logo_image":"TestSample","locale_code":"TestSample"}'));
}
/**
* Gets Object Instance with Json data filled in
* @return Presentation
*/
public static function getObject()
{
return new Presentation(self::getJson());
}
/**
* Tests for Serialization and Deserialization Issues
* @return Presentation
*/
public function testSerializationDeserialization()
{
$obj = new Presentation(self::getJson());
$this->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);
}
}

View File

@@ -2,6 +2,11 @@
namespace PayPal\Test\Api; 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; use PayPal\Api\WebProfile;
/** /**
@@ -11,73 +16,219 @@ use PayPal\Api\WebProfile;
*/ */
class WebProfileTest extends \PHPUnit_Framework_TestCase class WebProfileTest extends \PHPUnit_Framework_TestCase
{ {
/**
public function testCreateprofileSerialization() * Gets Json String of Object WebProfile
* @return string
*/
public static function getJson()
{ {
$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"}}'; return json_encode(json_decode('{"id":"TestSample","name":"TestSample","flow_config":' .FlowConfigTest::getJson() . ',"input_fields":' .InputFieldsTest::getJson() . ',"presentation":' .PresentationTest::getJson() . '}'));
$requestBodyEncoded = json_encode(json_decode($requestBody, true)); }
$object = new WebProfile($requestBodyEncoded);
$json = $object->toJson(); /**
$this->assertEquals($requestBodyEncoded, $json); * Gets Object Instance with Json data filled in
* @return WebProfile
*/
public static function getObject()
{
return new WebProfile(self::getJson());
} }
/** /**
* @group integration * Tests for Serialization and Deserialization Issues
* @return WebProfile
*/ */
public function testCreateprofileOperation() public function testSerializationDeserialization()
{ {
$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"}}'; $obj = new WebProfile(self::getJson());
$requestBodyEncoded = json_encode(json_decode($requestBody, true)); $this->assertNotNull($obj);
$object = new WebProfile($requestBodyEncoded); $this->assertNotNull($obj->getId());
$response = $object->create(null); $this->assertNotNull($obj->getName());
$this->assertNotNull($response); $this->assertNotNull($obj->getFlowConfig());
return $response->getId(); $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());
}
/**
* @depends testSerializationDeserialization
* @param WebProfile $obj
*/
public function testDeprecatedGetters($obj)
{
$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 * @dataProvider mockProvider
* @group integration * @param WebProfile $obj
*/ */
public function testGetprofileOperation($profileId) public function testCreate($obj, $mockApiContext)
{ {
$response = WebProfile::get($profileId, null); $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall')
$this->assertNotNull($response); ->disableOriginalConstructor()
$this->assertEquals($response->getId(), $profileId); ->getMock();
$this->assertEquals("http://www.ebay.com", $response->getPresentation()->getLogoImage());
$this->assertEquals(1, $response->getInputFields()->getNoShipping()); $mockPPRestCall->expects($this->any())
$this->assertEquals(1, $response->getInputFields()->getAddressOverride()); ->method('execute')
$this->assertEquals("billing", $response->getFlowConfig()->getLandingPageType()); ->will($this->returnValue(
$this->assertEquals("http://www.ebay.com", $response->getFlowConfig()->getBankTxnPendingUrl()); CreateProfileResponseTest::getJson()
return $response->getId(); ));
$result = $obj->create($mockApiContext, $mockPPRestCall);
$this->assertNotNull($result);
} }
public function testValidationerrorSerialization()
{
$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);
$json = $object->toJson();
$this->assertEquals($requestBodyEncoded, $json);
}
/** /**
* @group integration * @dataProvider mockProvider
* @expectedException PayPal\Exception\PPConnectionException * @param WebProfile $obj
* @expectedExceptionCode 400
*/ */
public function testValidationerrorOperation() public function testUpdate($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"}}'; $mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall')
$requestBodyEncoded = json_encode(json_decode($requestBody, true)); ->disableOriginalConstructor()
$object = new WebProfile($requestBodyEncoded); ->getMock();
$response = $object->create(null);
return $response->getId(); $mockPPRestCall->expects($this->any())
->method('execute')
->will($this->returnValue(
true
));
$result = $obj->update($mockApiContext, $mockPPRestCall);
$this->assertNotNull($result);
}
/**
* @dataProvider mockProvider
* @param WebProfile $obj
*/
public function testPartialUpdate($obj, $mockApiContext)
{
$mockPPRestCall = $this->getMockBuilder('\PayPal\Transport\PPRestCall')
->disableOriginalConstructor()
->getMock();
$mockPPRestCall->expects($this->any())
->method('execute')
->will($this->returnValue(
true
));
$patch = array(PatchTest::getObject());
$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);
}
/**
* @dataProvider mockProvider
* @param WebProfile $obj
*/
public function testGetList($obj, $mockApiContext)
{
$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)
);
}
} }

View File

@@ -0,0 +1,50 @@
<?php
use PayPal\Auth\Openid\PPOpenIdAddress;
/**
* Test class for PPOpenIdAddress.
*
*/
class PPOpenIdAddressTest extends \PHPUnit_Framework_TestCase
{
/** @var PPOpenIdAddress */
private $addr;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->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);
}
}

View File

@@ -0,0 +1,45 @@
<?php
use PayPal\Auth\Openid\PPOpenIdError;
/**
* Test class for PPOpenIdError.
*
*/
class PPOpenIdErrorTest extends PHPUnit_Framework_TestCase
{
/** @var PPOpenIdError */
private $error;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->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);
}
}

View File

@@ -0,0 +1,93 @@
<?php
use PayPal\Common\PPApiContext;
use PayPal\Auth\Openid\PPOpenIdSession;
/**
* Test class for PPOpenIdSession.
*
*/
class PPOpenIdSessionTest extends \PHPUnit_Framework_TestCase
{
private $context;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->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");
}
}

View File

@@ -0,0 +1,76 @@
<?php
use PayPal\Auth\Openid\PPOpenIdTokeninfo;
/**
* Test class for PPOpenIdTokeninfo.
*
*/
class PPOpenIdTokeninfoTest extends \PHPUnit_Framework_TestCase
{
/** @var PPOpenIdTokeninfo */
public $token;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
$this->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' => '<FILLME>',
'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);
}
}

View File

@@ -0,0 +1,60 @@
<?php
use PayPal\Auth\Openid\PPOpenIdUserinfo;
/**
* Test class for PPOpenIdUserinfo.
*
*/
class PPOpenIdUserinfoTest extends \PHPUnit_Framework_TestCase
{
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp()
{
}
/**
* 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()
{
$user = new PPOpenIdUserinfo();
$user->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'));
}
}

View File

@@ -80,7 +80,7 @@ class ModelTest extends \PHPUnit_Framework_TestCase
$this->assertEquals("test", $obj->getName()); $this->assertEquals("test", $obj->getName());
$this->assertEquals("description", $obj->getDescription()); $this->assertEquals("description", $obj->getDescription());
} catch (\PHPUnit_Framework_Error_Notice $ex) { } catch (\PHPUnit_Framework_Error_Notice $ex) {
echo $ex->getMessage(); // No need to do anything
} }
} }

View File

@@ -1,45 +0,0 @@
<?php
// namespace PayPal\Test\Rest;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\Call;
use PayPal\Test\Constants;
class CallTest
{
public function testExecuteWithExplicitCredentials()
{
$cred = new OAuthTokenCredential(Constants::CLIENT_ID, Constants::CLIENT_SECRET);
$data = '"request":"test message"';
$call = new Call();
$ret = $call->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);
}
}