From 84660cbb2a556fd24f564cdcf48f336d28db6193 Mon Sep 17 00:00:00 2001
From: japatel
Date: Mon, 20 Oct 2014 12:04:41 -0500
Subject: [PATCH] Updates to LIPP & Future Payments
- Updated LIPP Sample code
- Updated Future Payments to have helper functions for retrieving access token
- Updated Logging Syntax to include timestamp and response json
---
lib/PayPal/Api/FuturePayment.php | 30 +-
lib/PayPal/Auth/OAuthTokenCredential.php | 507 ++++++++++--------
lib/PayPal/Auth/Openid/PPOpenIdSession.php | 3 +
lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php | 11 +-
lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php | 2 +
lib/PayPal/Core/PPHttpConnection.php | 12 +-
lib/PayPal/Core/PPLoggingManager.php | 7 +-
lib/PayPal/Transport/PPRestCall.php | 1 -
sample/bootstrap.php | 1 +
sample/doc/assets/behavior.js | 126 +++++
sample/doc/invoice/CreateInvoice.html | 2 +-
sample/doc/invoice/GetInvoice.html | 2 +-
sample/doc/invoice/RemindInvoice.html | 2 +-
sample/doc/invoice/SendInvoice.html | 2 +-
.../GenerateAccessTokenFromRefreshToken.html | 15 +
sample/doc/lipp/GetUserInfo.html | 25 +
sample/doc/lipp/ObtainUserConsent.html | 18 +
sample/doc/lipp/UserConsentRedirect.html | 23 +
sample/doc/payments/CreateFuturePayment.html | 13 +-
.../payments/CreatePaymentUsingSavedCard.html | 2 +-
sample/doc/payments/ExecutePayment.html | 4 +-
sample/doc/payments/GetPayment.html | 2 +-
sample/doc/vault/GetCreditCard.html | 2 +-
sample/index.html | 44 ++
sample/invoice/CreateInvoice.php | 2 +-
sample/invoice/GetInvoice.php | 2 +-
sample/invoice/RemindInvoice.php | 2 +-
sample/invoice/SendInvoice.php | 2 +-
.../GenerateAccessTokenFromRefreshToken.php} | 15 +-
sample/lipp/GetUserInfo.php | 37 ++
sample/lipp/ObtainUserConsent.php | 22 +
sample/lipp/UserConsentRedirect.php | 28 +
sample/oauth/ObtainUserConsent.php | 20 -
sample/oauth/UserConsentRedirect.php | 36 --
sample/payments/CreateFuturePayment.php | 15 +-
sample/payments/CreatePayment.php | 258 ++++-----
sample/payments/CreatePaymentUsingPayPal.php | 250 ++++-----
.../payments/CreatePaymentUsingSavedCard.php | 234 ++++----
sample/payments/ExecutePayment.php | 82 +--
sample/payments/GetPayment.php | 78 +--
sample/sdk_config.ini | 4 +-
sample/vault/GetCreditCard.php | 2 +-
42 files changed, 1156 insertions(+), 789 deletions(-)
create mode 100644 sample/doc/lipp/GenerateAccessTokenFromRefreshToken.html
create mode 100644 sample/doc/lipp/GetUserInfo.html
create mode 100644 sample/doc/lipp/ObtainUserConsent.html
create mode 100644 sample/doc/lipp/UserConsentRedirect.html
rename sample/{oauth/ObtainUserConsentFromRefreshToken.php => lipp/GenerateAccessTokenFromRefreshToken.php} (62%)
create mode 100644 sample/lipp/GetUserInfo.php
create mode 100644 sample/lipp/ObtainUserConsent.php
create mode 100644 sample/lipp/UserConsentRedirect.php
delete mode 100644 sample/oauth/ObtainUserConsent.php
delete mode 100644 sample/oauth/UserConsentRedirect.php
diff --git a/lib/PayPal/Api/FuturePayment.php b/lib/PayPal/Api/FuturePayment.php
index 5883a63..f96d4fa 100644
--- a/lib/PayPal/Api/FuturePayment.php
+++ b/lib/PayPal/Api/FuturePayment.php
@@ -21,7 +21,8 @@ class FuturePayment extends Payment
* @param $correlationId
* @return $this
*/
- public function create($apiContext = null, $correlationId = null) {
+ public function create($apiContext = null, $correlationId = null)
+ {
if ($apiContext == null) {
$apiContext = new ApiContext(self::$credential);
}
@@ -45,4 +46,31 @@ class FuturePayment extends Payment
return $this;
}
+
+ /**
+ * Get a Refresh Token from Authorization Code
+ *
+ * @param $authorizationCode
+ * @param ApiContext $apiContext
+ * @return string|null refresh token
+ */
+ public static function getRefreshToken($authorizationCode, $apiContext = null)
+ {
+ $apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
+ $credential = $apiContext->getCredential();
+ return $credential->getRefreshToken($apiContext->getConfig(), $authorizationCode);
+ }
+
+ /**
+ * Updates Access Token using long lived refresh token
+ *
+ * @param string|null $refreshToken
+ * @param ApiContext $apiContext
+ * @return void
+ */
+ public function updateAccessToken($refreshToken, $apiContext)
+ {
+ $apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
+ $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refreshToken);
+ }
}
diff --git a/lib/PayPal/Auth/OAuthTokenCredential.php b/lib/PayPal/Auth/OAuthTokenCredential.php
index 302f675..b27b097 100644
--- a/lib/PayPal/Auth/OAuthTokenCredential.php
+++ b/lib/PayPal/Auth/OAuthTokenCredential.php
@@ -1,236 +1,271 @@
-clientId = $clientId;
- $this->clientSecret = $clientSecret;
- $this->logger = PPLoggingManager::getInstance(__CLASS__);
- }
-
- /**
- * Get AccessToken
- *
- * @param $config
- *
- * @return null|string
- */
- public function getAccessToken($config)
- {
- // Check if Access Token is not null and has not expired.
- // The API returns expiry time as a relative time unit
- // We use a buffer time when checking for token expiry to account
- // for API call delays and any delay between the time the token is
- // retrieved and subsequently used
- if (
- $this->accessToken != null &&
- (time() - $this->tokenCreateTime) > ($this->tokenExpiresIn - self::$expiryBufferTime)
- ) {
- $this->accessToken = null;
- }
-
- // If accessToken is Null, obtain a new token
- if ($this->accessToken == null) {
- $this->updateAccessToken($config);
- }
-
- return $this->accessToken;
- }
-
- /**
- * Get a Refresh Token from Authorization Code
- *
- * @param $config
- * @param $authorizationCode
- * @return string|null
- */
- public function getRefreshToken($config, $authorizationCode) //Which comes from Mobile.
- {
- $payload =
- "grant_type=authorization_code&code=".
- $authorizationCode.
- "&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=token";
- $jsonResponse = $this->getToken($config, $payload);
-
- if ($jsonResponse != null && isset($jsonResponse["refresh_token"])) {
- return $jsonResponse['refresh_token'];
- }
- }
-
- /**
- * Updates Access Token based on given input
- *
- * @param $config
- * @param string|null $refreshToken
- * @return string
- */
- public function updateAccessToken($config, $refreshToken = null)
- {
- $this->generateAccessToken($config, $refreshToken);
- return $this->accessToken;
- }
-
- /**
- * Retrieves the token based on the input configuration
- *
- * @param array $config
- * @param string $payload
- * @return mixed
- * @throws PPConfigurationException
- * @throws \PayPal\Exception\PPConnectionException
- */
- private function getToken($config, $payload)
- {
- $base64ClientID = base64_encode($this->clientId . ":" . $this->clientSecret);
- $headers = array(
- "User-Agent" => PPUserAgent::getValue(RestHandler::$sdkName, RestHandler::$sdkVersion),
- "Authorization" => "Basic " . $base64ClientID,
- "Accept" => "*/*"
- );
-
- $httpConfiguration = $this->getOAuthHttpConfiguration($config);
- $httpConfiguration->setHeaders($headers);
-
- $connection = new PPHttpConnection($httpConfiguration, $config);
- $res = $connection->execute($payload);
- $jsonResponse = json_decode($res, true);
-
- if ($jsonResponse == null || !isset($jsonResponse["access_token"]) || !isset($jsonResponse["expires_in"])) {
- $this->accessToken = null;
- $this->tokenExpiresIn = null;
- $this->logger->warning(
- "Could not generate new Access token. Invalid response from server: " . $jsonResponse
- );
- } else {
- $this->accessToken = $jsonResponse["access_token"];
- $this->tokenExpiresIn = $jsonResponse["expires_in"];
- }
- $this->tokenCreateTime = time();
- return $jsonResponse;
- }
-
-
- /**
- * Generates a new access token
- *
- * @param array $config
- * @return null
- */
- private function generateAccessToken($config, $refreshToken = null)
- {
- $payload = "grant_type=client_credentials";
- if ($refreshToken != null) {
- // If the refresh token is provided, it would get access token using refresh token
- // Used for Future Payments
- $payload = "grant_type=refresh_token&refresh_token=$refreshToken";
- }
- $this->getToken($config, $payload);
-
- return $this->accessToken;
- }
-
- /**
- * Get HttpConfiguration object for OAuth API
- *
- * @param array $config
- *
- * @return PPHttpConfig
- * @throws \PayPal\Exception\PPConfigurationException
- */
- private function getOAuthHttpConfiguration($config)
- {
- if (isset($config['oauth.EndPoint'])) {
- $baseEndpoint = $config['oauth.EndPoint'];
- } else if (isset($config['service.EndPoint'])) {
- $baseEndpoint = $config['service.EndPoint'];
- } else if (isset($config['mode'])) {
- switch (strtoupper($config['mode'])) {
- case 'SANDBOX':
- $baseEndpoint = PPConstants::REST_SANDBOX_ENDPOINT;
- break;
- case 'LIVE':
- $baseEndpoint = PPConstants::REST_LIVE_ENDPOINT;
- break;
- default:
- throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live');
- }
- } else {
- throw new PPConfigurationException(
- 'You must set one of service.endpoint or mode parameters in your configuration'
- );
- }
-
- $baseEndpoint = rtrim(trim($baseEndpoint), '/');
-
- return new PPHttpConfig($baseEndpoint . "/v1/oauth2/token", "POST");
- }
-}
+clientId = $clientId;
+ $this->clientSecret = $clientSecret;
+ $this->logger = PPLoggingManager::getInstance(__CLASS__);
+ }
+
+ /**
+ * Get Client ID
+ *
+ * @return string
+ */
+ public function getClientId()
+ {
+ return $this->clientId;
+ }
+
+ /**
+ * Get Client Secret
+ *
+ * @return string
+ */
+ public function getClientSecret()
+ {
+ return $this->clientSecret;
+ }
+
+ /**
+ * Get AccessToken
+ *
+ * @param $config
+ *
+ * @return null|string
+ */
+ public function getAccessToken($config)
+ {
+ // Check if Access Token is not null and has not expired.
+ // The API returns expiry time as a relative time unit
+ // We use a buffer time when checking for token expiry to account
+ // for API call delays and any delay between the time the token is
+ // retrieved and subsequently used
+ if (
+ $this->accessToken != null &&
+ (time() - $this->tokenCreateTime) > ($this->tokenExpiresIn - self::$expiryBufferTime)
+ ) {
+ $this->accessToken = null;
+ }
+
+ // If accessToken is Null, obtain a new token
+ if ($this->accessToken == null) {
+ $this->updateAccessToken($config);
+ }
+
+ return $this->accessToken;
+ }
+
+ /**
+ * Get a Refresh Token from Authorization Code
+ *
+ * @param $config
+ * @param $authorizationCode
+ * @param array $params optional arrays to override defaults
+ * @return string|null
+ */
+ public function getRefreshToken($config, $authorizationCode = null, $params = array())
+ {
+ static $allowedParams = array(
+ 'grant_type' => 'authorization_code',
+ 'code' => 1,
+ 'redirect_uri' => 'urn:ietf:wg:oauth:2.0:oob',
+ 'response_type' => 'token'
+ );
+
+ $params = is_array($params) ? $params : array();
+ if ($authorizationCode) {
+ //Override the authorizationCode if value is explicitly set
+ $params['code'] = $authorizationCode;
+ }
+ $payload = http_build_query(array_merge($allowedParams, array_intersect_key($params, $allowedParams)));
+
+ $response = $this->getToken($config, $this->clientId, $this->clientSecret, $payload);
+
+ if ($response != null && isset($response["refresh_token"])) {
+ return $response['refresh_token'];
+ }
+ }
+
+ /**
+ * Updates Access Token based on given input
+ *
+ * @param $config
+ * @param string|null $refreshToken
+ * @return string
+ */
+ public function updateAccessToken($config, $refreshToken = null)
+ {
+ $this->generateAccessToken($config, $refreshToken);
+ return $this->accessToken;
+ }
+
+ /**
+ * Retrieves the token based on the input configuration
+ *
+ * @param array $config
+ * @param string $payload
+ * @return mixed
+ * @throws PPConfigurationException
+ * @throws \PayPal\Exception\PPConnectionException
+ */
+ private function getToken($config, $clientId, $clientSecret, $payload)
+ {
+ $base64ClientID = base64_encode($clientId . ":" . $clientSecret);
+ $headers = array(
+ "User-Agent" => PPUserAgent::getValue(RestHandler::$sdkName, RestHandler::$sdkVersion),
+ "Authorization" => "Basic " . $base64ClientID,
+ "Accept" => "*/*"
+ );
+
+ $httpConfiguration = self::getOAuthHttpConfiguration($config);
+ $httpConfiguration->setHeaders($headers);
+
+ $connection = new PPHttpConnection($httpConfiguration, $config);
+ $res = $connection->execute($payload);
+ $response = json_decode($res, true);
+
+ return $response;
+ }
+
+
+ /**
+ * Generates a new access token
+ *
+ * @param array $config
+ * @return null
+ */
+ private function generateAccessToken($config, $refreshToken = null)
+ {
+ $params = array('grant_type' => 'client_credentials');
+ if ($refreshToken != null) {
+ // If the refresh token is provided, it would get access token using refresh token
+ // Used for Future Payments
+ $params['grant_type'] = 'refresh_token';
+ $params['refresh_token'] = $refreshToken;
+ }
+ $payload = http_build_query($params);
+ $response = $this->getToken($config, $this->clientId, $this->clientSecret, $payload);
+
+ if ($response == null || !isset($response["access_token"]) || !isset($response["expires_in"])) {
+ $this->accessToken = null;
+ $this->tokenExpiresIn = null;
+ $this->logger->warning(
+ "Could not generate new Access token. Invalid response from server: " . $response
+ );
+ } else {
+ $this->accessToken = $response["access_token"];
+ $this->tokenExpiresIn = $response["expires_in"];
+ }
+ $this->tokenCreateTime = time();
+
+ return $this->accessToken;
+ }
+
+ /**
+ * Get HttpConfiguration object for OAuth API
+ *
+ * @param array $config
+ *
+ * @return PPHttpConfig
+ * @throws \PayPal\Exception\PPConfigurationException
+ */
+ private static function getOAuthHttpConfiguration($config)
+ {
+ if (isset($config['oauth.EndPoint'])) {
+ $baseEndpoint = $config['oauth.EndPoint'];
+ } else if (isset($config['service.EndPoint'])) {
+ $baseEndpoint = $config['service.EndPoint'];
+ } else if (isset($config['mode'])) {
+ switch (strtoupper($config['mode'])) {
+ case 'SANDBOX':
+ $baseEndpoint = PPConstants::REST_SANDBOX_ENDPOINT;
+ break;
+ case 'LIVE':
+ $baseEndpoint = PPConstants::REST_LIVE_ENDPOINT;
+ break;
+ default:
+ throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live');
+ }
+ } else {
+ throw new PPConfigurationException(
+ 'You must set one of service.endpoint or mode parameters in your configuration'
+ );
+ }
+
+ $baseEndpoint = rtrim(trim($baseEndpoint), '/');
+
+ return new PPHttpConfig($baseEndpoint . "/v1/oauth2/token", "POST");
+ }
+}
diff --git a/lib/PayPal/Auth/Openid/PPOpenIdSession.php b/lib/PayPal/Auth/Openid/PPOpenIdSession.php
index 598ca73..1331294 100644
--- a/lib/PayPal/Auth/Openid/PPOpenIdSession.php
+++ b/lib/PayPal/Auth/Openid/PPOpenIdSession.php
@@ -28,6 +28,9 @@ class PPOpenIdSession
if ($apiContext->get($clientId)) {
$clientId = $apiContext->get($clientId);
}
+
+ $clientId = $clientId ? $clientId : $apiContext->getCredential()->getClientId();
+
$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)) {
diff --git a/lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php b/lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php
index 8940259..85d6c26 100644
--- a/lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php
+++ b/lib/PayPal/Auth/Openid/PPOpenIdTokeninfo.php
@@ -164,6 +164,7 @@ class PPOpenIdTokeninfo extends ResourceModel
if (!array_key_exists('grant_type', $params)) {
$params['grant_type'] = 'authorization_code';
}
+ $apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
if (sizeof($apiContext->get($clientId)) > 0) {
$clientId = $apiContext->get($clientId);
@@ -172,6 +173,10 @@ class PPOpenIdTokeninfo extends ResourceModel
if (sizeof($apiContext->get($clientSecret)) > 0) {
$clientSecret = $apiContext->get($clientSecret);
}
+
+ $clientId = $clientId ? $clientId : $apiContext->getCredential()->getClientId();
+ $clientSecret = $clientSecret ? $clientSecret : $apiContext->getCredential()->getClientSecret();
+
$json = self::executeCall(
"/v1/identity/openidconnect/tokenservice",
"POST",
@@ -205,6 +210,7 @@ class PPOpenIdTokeninfo extends ResourceModel
public function createFromRefreshToken($params, $apiContext = null)
{
static $allowedParams = array('grant_type' => 1, 'refresh_token' => 1, 'scope' => 1);
+ $apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
if (!array_key_exists('grant_type', $params)) {
$params['grant_type'] = 'refresh_token';
@@ -213,13 +219,16 @@ class PPOpenIdTokeninfo extends ResourceModel
$params['refresh_token'] = $this->getRefreshToken();
}
+ $clientId = isset($params['client_id']) ? $params['client_id'] : $apiContext->getCredential()->getClientId();
+ $clientSecret = isset($params['client_secret']) ? $params['client_secret'] : $apiContext->getCredential()->getClientSecret();
+
$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'])
+ 'Authorization' => 'Basic ' . base64_encode($clientId . ":" . $clientSecret)
),
$apiContext
);
diff --git a/lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php b/lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php
index e7d0544..f49d343 100644
--- a/lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php
+++ b/lib/PayPal/Auth/Openid/PPOpenIdUserinfo.php
@@ -466,6 +466,8 @@ class PPOpenIdUserinfo extends ResourceModel
{
static $allowedParams = array('schema' => 1);
+ $params = is_array($params) ? $params : array();
+
if (!array_key_exists('schema', $params)) {
$params['schema'] = 'openid';
}
diff --git a/lib/PayPal/Core/PPHttpConnection.php b/lib/PayPal/Core/PPHttpConnection.php
index f520642..8f0e8e9 100644
--- a/lib/PayPal/Core/PPHttpConnection.php
+++ b/lib/PayPal/Core/PPHttpConnection.php
@@ -79,8 +79,7 @@ class PPHttpConnection
public function execute($data)
{
//Initialize the logger
- $this->logger->fine("Connecting to " . $this->httpConfig->getUrl());
- $this->logger->fine("Payload " . $data);
+ $this->logger->info($this->httpConfig->getMethod() . ' ' . $this->httpConfig->getUrl());
//Initialize Curl Options
$ch = curl_init($this->httpConfig->getUrl());
@@ -100,18 +99,19 @@ class PPHttpConnection
//Default Option if Method not of given types in switch case
if ($this->httpConfig->getMethod() != NULL) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->httpConfig->getMethod());
- $this->logger->info("Method : " . $this->httpConfig->getMethod());
}
//Logging Each Headers for debugging purposes
foreach ($this->getHttpHeaders() as $header) {
//TODO: Strip out credentials and other secure info when logging.
- $this->logger->info("Adding header $header");
+ $this->logger->fine($header);
}
+ $this->logger->fine("Payload : " . $data . "\n");
//Execute Curl Request
$result = curl_exec($ch);
+
//Retry if Certificate Exception
if (curl_errno($ch) == 60) {
$this->logger->info("Invalid or no certificate authority found - Retrying using bundled CA certs file");
@@ -151,6 +151,7 @@ class PPHttpConnection
"Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}. " .
"Retried $retries times."
);
+ $this->logger->fine("Response : " . $result . "\n\n");
$ex->setData($result);
throw $ex;
} else if ($httpStatus < 200 || $httpStatus >= 300) {
@@ -159,10 +160,13 @@ class PPHttpConnection
"Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}.",
$httpStatus
);
+ $this->logger->fine("Response : " . $result . "\n\n");
$ex->setData($result);
throw $ex;
}
+ $this->logger->fine("Response : " . $result . "\n\n");
+
//Return result object
return $result;
}
diff --git a/lib/PayPal/Core/PPLoggingManager.php b/lib/PayPal/Core/PPLoggingManager.php
index 29e162b..a2eda13 100644
--- a/lib/PayPal/Core/PPLoggingManager.php
+++ b/lib/PayPal/Core/PPLoggingManager.php
@@ -70,6 +70,11 @@ class PPLoggingManager
*/
public function __construct()
{
+ // To suppress the warning during the date() invocation in logs, we would default the timezone to GMT.
+ if (!ini_get('date.timezone')) {
+ date_default_timezone_set('GMT');
+ }
+
$config = PPConfigManager::getInstance()->getConfigHashmap();
$this->isLoggingEnabled = (array_key_exists('log.LogEnabled', $config) && $config['log.LogEnabled'] == '1');
@@ -93,7 +98,7 @@ class PPLoggingManager
private function log($message, $level = PPLoggingLevel::INFO)
{
if ($this->isLoggingEnabled && ($level <= $this->loggingLevel)) {
- error_log($this->loggerName . ": $message\n", 3, $this->loggerFile);
+ error_log("[" . date('d-m-Y h:i:s') . "] " . $this->loggerName . ": $message\n", 3, $this->loggerFile);
}
}
diff --git a/lib/PayPal/Transport/PPRestCall.php b/lib/PayPal/Transport/PPRestCall.php
index ab9b12a..cf3ad8b 100644
--- a/lib/PayPal/Transport/PPRestCall.php
+++ b/lib/PayPal/Transport/PPRestCall.php
@@ -72,7 +72,6 @@ class PPRestCall
}
$connection = new PPHttpConnection($httpConfig, $config);
$response = $connection->execute($data);
- $this->logger->fine($response . PHP_EOL);
return $response;
}
diff --git a/sample/bootstrap.php b/sample/bootstrap.php
index 87728bb..abed4b9 100644
--- a/sample/bootstrap.php
+++ b/sample/bootstrap.php
@@ -23,6 +23,7 @@ use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
error_reporting(E_ALL);
+ini_set('display_errors', '1');
// Replace these values by entering your own ClientId and Secret by visiting https://developer.paypal.com/webapps/developer/applications/myapps
$clientId = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS';
diff --git a/sample/doc/assets/behavior.js b/sample/doc/assets/behavior.js
index 291e9f0..1188e5c 100644
--- a/sample/doc/assets/behavior.js
+++ b/sample/doc/assets/behavior.js
@@ -343,6 +343,132 @@ f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3
]
}
]
+ }, {
+ "type": "folder",
+ "data": {
+ "path": "lipp",
+ "title": "lipp"
+ },
+ "depth": 1,
+ "children": [
+ {
+ "type": "file",
+ "data": {
+ "language": {
+ "nameMatchers": [{}, ".fbp"],
+ "pygmentsLexer": "php",
+ "singleLineComment": ["//"],
+ "ignorePrefix": "}",
+ "foldPrefix": "^",
+ "name": "PHP"
+ },
+ "sourcePath": "/Users/japatel/Documents/workspace/Server-SDK/rest-api-sdk-php/sample/lipp/GenerateAccessTokenFromRefreshToken.php",
+ "projectPath": "lipp/GenerateAccessTokenFromRefreshToken.php",
+ "targetPath": "lipp/GenerateAccessTokenFromRefreshToken",
+ "pageTitle": "lipp/GenerateAccessTokenFromRefreshToken",
+ "title": "GenerateAccessTokenFromRefreshToken"
+ },
+ "depth": 2,
+ "outline": [
+ {
+ "type": "heading",
+ "data": {
+ "level": 3,
+ "title": "Obtain Access Token From Refresh Token",
+ "slug": "obtain-access-token-from-refresh-token"
+ },
+ "depth": 3
+ }
+ ]
+ }, {
+ "type": "file",
+ "data": {
+ "language": {
+ "nameMatchers": [{}, ".fbp"],
+ "pygmentsLexer": "php",
+ "singleLineComment": ["//"],
+ "ignorePrefix": "}",
+ "foldPrefix": "^",
+ "name": "PHP"
+ },
+ "sourcePath": "/Users/japatel/Documents/workspace/Server-SDK/rest-api-sdk-php/sample/lipp/GetUserInfo.php",
+ "projectPath": "lipp/GetUserInfo.php",
+ "targetPath": "lipp/GetUserInfo",
+ "pageTitle": "lipp/GetUserInfo",
+ "title": "GetUserInfo"
+ },
+ "depth": 2,
+ "outline": [
+ {
+ "type": "heading",
+ "data": {
+ "level": 3,
+ "title": "Obtain Access Token From Refresh Token",
+ "slug": "obtain-access-token-from-refresh-token"
+ },
+ "depth": 3
+ }
+ ]
+ }, {
+ "type": "file",
+ "data": {
+ "language": {
+ "nameMatchers": [{}, ".fbp"],
+ "pygmentsLexer": "php",
+ "singleLineComment": ["//"],
+ "ignorePrefix": "}",
+ "foldPrefix": "^",
+ "name": "PHP"
+ },
+ "sourcePath": "/Users/japatel/Documents/workspace/Server-SDK/rest-api-sdk-php/sample/lipp/ObtainUserConsent.php",
+ "projectPath": "lipp/ObtainUserConsent.php",
+ "targetPath": "lipp/ObtainUserConsent",
+ "pageTitle": "lipp/ObtainUserConsent",
+ "title": "ObtainUserConsent"
+ },
+ "depth": 2,
+ "outline": [
+ {
+ "type": "heading",
+ "data": {
+ "level": 3,
+ "title": "Get User Consent URL",
+ "slug": "get-user-consent-url"
+ },
+ "depth": 3
+ }
+ ]
+ }, {
+ "type": "file",
+ "data": {
+ "language": {
+ "nameMatchers": [{}, ".fbp"],
+ "pygmentsLexer": "php",
+ "singleLineComment": ["//"],
+ "ignorePrefix": "}",
+ "foldPrefix": "^",
+ "name": "PHP"
+ },
+ "sourcePath": "/Users/japatel/Documents/workspace/Server-SDK/rest-api-sdk-php/sample/lipp/UserConsentRedirect.php",
+ "projectPath": "lipp/UserConsentRedirect.php",
+ "targetPath": "lipp/UserConsentRedirect",
+ "pageTitle": "lipp/UserConsentRedirect",
+ "title": "UserConsentRedirect"
+ },
+ "depth": 2,
+ "outline": [
+ {
+ "type": "heading",
+ "data": {
+ "level": 3,
+ "title": "User Consent Response",
+ "slug": "user-consent-response"
+ },
+ "depth": 3
+ }
+ ]
+ }
+ ]
}, {
"type": "folder",
"data": {
diff --git a/sample/doc/invoice/CreateInvoice.html b/sample/doc/invoice/CreateInvoice.html
index 4f80c2f..1c43f39 100644
--- a/sample/doc/invoice/CreateInvoice.html
+++ b/sample/doc/invoice/CreateInvoice.html
@@ -22,7 +22,7 @@ required for invoice APIs
->setShippingInfo(new ShippingInfo());
$invoice ->getMerchantInfo()
- ->setEmail("PPX.DevNet-facilitator@gmail.com" )
+ ->setEmail("jaypatel512-facilitator@hotmail.com" )
->setFirstName("Dennis" )
->setLastName("Doctor" )
->setbusinessName("Medical Professionals, LLC" )
diff --git a/sample/doc/invoice/GetInvoice.html b/sample/doc/invoice/GetInvoice.html
index 6674109..cb78d85 100644
--- a/sample/doc/invoice/GetInvoice.html
+++ b/sample/doc/invoice/GetInvoice.html
@@ -3,7 +3,7 @@
an invoice.
require __DIR__ . '/../bootstrap.php' ;
use PayPal \Api \Invoice ;
-$invoiceId = "INV2-9DRB-YTHU-2V9Q-7Q24" ;
get method
on the Invoice class by passing a valid
Invoice ID
-(See bootstrap.php for more on ApiContext)
$invoice = Invoice::get("INV2-9CAH-K5G7-2JPL-G4B4" , $apiContext );
$invoice = Invoice::get("INV2-W4LC-6QS9-JZ62-VE4P" , $apiContext );
$notify = new Notification();
diff --git a/sample/doc/invoice/SendInvoice.html b/sample/doc/invoice/SendInvoice.html
index 2bae56b..e93baac 100644
--- a/sample/doc/invoice/SendInvoice.html
+++ b/sample/doc/invoice/SendInvoice.html
@@ -9,7 +9,7 @@ a legitimate invoice to the payer
$invoice = Invoice::get("INV2-9DRB-YTHU-2V9Q-7Q24" , $apiContext );
$invoice = Invoice::get("INV2-W4LC-6QS9-JZ62-VE4P" , $apiContext );
$sendStatus =
$invoice ->send(
$apiContext );
}
catch (PayPal\
Exception \PPConnectionException
$ex ) {
diff --git a/sample/doc/lipp/GenerateAccessTokenFromRefreshToken.html b/sample/doc/lipp/GenerateAccessTokenFromRefreshToken.html
new file mode 100644
index 0000000..9fd569f
--- /dev/null
+++ b/sample/doc/lipp/GenerateAccessTokenFromRefreshToken.html
@@ -0,0 +1,15 @@
+
lipp/GenerateAccessTokenFromRefreshToken
require __DIR__ . '/../bootstrap.php' ;
+use PayPal \Auth \Openid \PPOpenIdTokeninfo ;
$refreshToken = 'yzX4AkmMyBKR4on7vB5he-tDu38s24Zy-kTibhSuqA8kTdy0Yinxj7NpAyULx0bxqC5G8dbXOt0aVMlMmtpiVmSzhcjVZhYDM7WUQLC9KpaXGBHyltJPkLLQkXE' ;
+
+try {
+
+ $tokenInfo = new PPOpenIdTokeninfo();
+ $tokenInfo = $tokenInfo ->createFromRefreshToken(array ('refresh_token' => $refreshToken ), $apiContext );
+
+} catch (PayPal\Exception \PPConnectionException $ex ) {
+ echo "Exception: " . $ex ->getMessage() . PHP_EOL;
+ var_dump($ex ->getData());
+ exit (1 );
+}
+
+print_result("Obtained Access Token From Refresh Token" , "Access Token" , $tokenInfo ->getAccessToken(), $tokenInfo );
\ No newline at end of file
diff --git a/sample/doc/lipp/GetUserInfo.html b/sample/doc/lipp/GetUserInfo.html
new file mode 100644
index 0000000..3c83cc1
--- /dev/null
+++ b/sample/doc/lipp/GetUserInfo.html
@@ -0,0 +1,25 @@
+
lipp/GetUserInfo
require __DIR__ . '/../bootstrap.php' ;
+
+use PayPal \Auth \OpenId \PPOpenIdTokenInfo ;
+use PayPal \Auth \OpenId \PPOpenIdUserInfo ;
$refreshToken = 'yzX4AkmMyBKR4on7vB5he-tDu38s24Zy-kTibhSuqA8kTdy0Yinxj7NpAyULx0bxqC5G8dbXOt0aVMlMmtpiVmSzhcjVZhYDM7WUQLC9KpaXGBHyltJPkLLQkXE' ;
+
+try {
+
+ $tokenInfo = new PPOpenIdTokeninfo();
+ $tokenInfo = $tokenInfo ->createFromRefreshToken(array ('refresh_token' => $refreshToken ), $apiContext );
+
+ $params = array ('access_token' => $tokenInfo ->getAccessToken());
+ $userInfo = PPOpenIdUserinfo::getUserinfo($params , $apiContext );
+
+} catch (PayPal\Exception \PPConnectionException $ex ) {
+ echo "Exception: " . $ex ->getMessage() . PHP_EOL;
+ var_dump($ex ->getData());
+ exit (1 );
+}
+
+print_result("User Information" , "User Info" , $userInfo ->getUserId(), $userInfo ->toJSON(JSON_PRETTY_PRINT));
\ No newline at end of file
diff --git a/sample/doc/lipp/ObtainUserConsent.html b/sample/doc/lipp/ObtainUserConsent.html
new file mode 100644
index 0000000..b8b1ca0
--- /dev/null
+++ b/sample/doc/lipp/ObtainUserConsent.html
@@ -0,0 +1,18 @@
+
lipp/ObtainUserConsent <?php
+
+require __DIR__ . '/../bootstrap.php' ;
+
+use PayPal \Auth \Openid \PPOpenIdSession ;
+
+$baseUrl = getBaseUrl() . '/UserConsentRedirect.php?success=true' ;
+$redirectUrl = PPOpenIdSession::getAuthorizationUrl(
+ $baseUrl ,
+ array ('profile' , 'email' , 'phone' ),
+ null ,
+ null ,
+ null ,
+ $apiContext
+);
+
+print_result("Generated the User Consent URL" , "URL" , null , '<a href="' . $redirectUrl . '" >Click Here to Obtain User Consent</a>' );
\ No newline at end of file
diff --git a/sample/doc/lipp/UserConsentRedirect.html b/sample/doc/lipp/UserConsentRedirect.html
new file mode 100644
index 0000000..d7aced4
--- /dev/null
+++ b/sample/doc/lipp/UserConsentRedirect.html
@@ -0,0 +1,23 @@
+
lipp/UserConsentRedirect <?php
+
+require __DIR__ . '/../bootstrap.php' ;
+
+use PayPal \Auth \Openid \PPOpenIdTokeninfo ;
+use PayPal \Exception \PPConnectionException ;
+
+session_start();
if (isset ($_GET ['success' ]) && $_GET ['success' ] == 'true' ) {
+
+ $code = $_GET ['code' ];
+
+ try {
$accessToken = PPOpenIdTokeninfo::createFromAuthorizationCode(array ('code' => $code ), null , null , $apiContext );
+ } catch (PPConnectionException $ex ) {
+ echo "Exception: " . $ex ->getMessage() . PHP_EOL;
+ var_dump($ex ->getData());
+ exit (1 );
+ }
+
+ print_result("Obtained Access Token" , "Access Token" , $accessToken ->getAccessToken(), $accessToken );
+
+}
\ No newline at end of file
diff --git a/sample/doc/payments/CreateFuturePayment.html b/sample/doc/payments/CreateFuturePayment.html
index 1b435e6..b60ebff 100644
--- a/sample/doc/payments/CreateFuturePayment.html
+++ b/sample/doc/payments/CreateFuturePayment.html
@@ -3,11 +3,8 @@
PayPal Account based Payment.
API used: /v1/payments/payment
require __DIR__ . '/../bootstrap.php' ;
use PayPal \Api \Amount ;
-use PayPal \Api \Details ;
-use PayPal \Api \Item ;
-use PayPal \Api \ItemList ;
use PayPal \Api \Payer ;
-use PayPal \Api \Payment ;
+use PayPal \Api \FuturePayment ;
use PayPal \Api \RedirectUrls ;
use PayPal \Api \Transaction ;
session_start();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true" )
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false" );
$payment = new Payment();
+the above types and intent set to 'sale'
$payment = new FuturePayment();
$payment ->setIntent("authorize" )
->setPayer($payer )
->setRedirectUrls($redirectUrls )
->setTransactions(array ($transaction ));
$authorizationCode = 'EF4Ds2Wv1JbHiU_UuhR5v-ftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY' ;
$correlationId =
'123123456' ;
+
You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.
$authorizationCode = 'EJfRuAqXEE95pdVMmOym_mftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY' ;
$correlationId = '123123456' ;
try {
$refreshToken = $apiContext ->getCredential()->getRefreshToken($apiContext ->getConfig(), $authorizationCode );
$apiContext ->getCredential()->updateAccessToken($apiContext ->getConfig(), $refreshToken );
$refreshToken = FuturePayment::getRefreshToken($authorizationCode , $apiContext );
$payment ->updateAccessToken($refreshToken , $apiContext );
$payment ->create($apiContext , $correlationId );
+Please note that currently future payments works only with PayPal as a funding instrument.
$payment ->create($apiContext , $correlationId );
} catch (PayPal\Exception \PPConnectionException $ex ) {
echo "Exception: " . $ex ->getMessage() . PHP_EOL;
diff --git a/sample/doc/payments/CreatePaymentUsingSavedCard.html b/sample/doc/payments/CreatePaymentUsingSavedCard.html
index 9811e94..bec2a1f 100644
--- a/sample/doc/payments/CreatePaymentUsingSavedCard.html
+++ b/sample/doc/payments/CreatePaymentUsingSavedCard.html
@@ -13,7 +13,7 @@ API used: /v1/payments/payment
use PayPal \Api \Transaction ;
$creditCardToken = new CreditCardToken();
-$creditCardToken ->setCreditCardId('CARD-29H07236G1554552FKINPBHQ' );
$fi = new FundingInstrument();
diff --git a/sample/doc/payments/ExecutePayment.html b/sample/doc/payments/ExecutePayment.html
index 6552112..92a84bd 100644
--- a/sample/doc/payments/ExecutePayment.html
+++ b/sample/doc/payments/ExecutePayment.html
@@ -22,10 +22,12 @@ when the user is redirected from paypal back to your site
$result = $payment ->execute($execution , $apiContext );
- echo "<html><body><pre>" ;
+ echo "<html><body><pre>" ;
echo $result ->toJSON(JSON_PRETTY_PRINT);
echo "</pre><a href='../index.html'>Back</a></body></html>" ;
} else {
+ echo "<html><body><h1>" ;
echo "User cancelled payment." ;
+ echo "</h1><a href='../index.html'>Back</a></body></html>" ;
}
Merchant Info
A resource representing merchant information that can be used to identify merchant