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());

Merchant Info

A resource representing merchant information that can be used to identify merchant

$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";

Retrieve Invoice

+$invoiceId = "INV2-W4LC-6QS9-JZ62-VE4P";

Retrieve Invoice

Retrieve the invoice object by calling the static get method on the Invoice class by passing a valid diff --git a/sample/doc/invoice/RemindInvoice.html b/sample/doc/invoice/RemindInvoice.html index 3789b92..fc2a4ae 100644 --- a/sample/doc/invoice/RemindInvoice.html +++ b/sample/doc/invoice/RemindInvoice.html @@ -10,7 +10,7 @@ an invoice to the payer

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);

Notification Object

+(See bootstrap.php for more on ApiContext)

$invoice = Invoice::get("INV2-W4LC-6QS9-JZ62-VE4P", $apiContext);

Notification Object

This would send a notification to both merchant as well the payer. The information of merchant and payer is retrieved from the invoice details

$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);

Send Invoice

+(See bootstrap.php for more on ApiContext)

$invoice = Invoice::get("INV2-W4LC-6QS9-JZ62-VE4P", $apiContext);

Send Invoice

Send a legitimate invoice to the payer with a valid ApiContext (See bootstrap.php for more on 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
lipp/GenerateAccessTokenFromRefreshToken.php
<?php

Obtain Access Token From Refresh Token

require __DIR__ . '/../bootstrap.php'; +use PayPal\Auth\Openid\PPOpenIdTokeninfo;

You can retrieve the refresh token by executing ObtainUserConsent.php and store the refresh token

$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
lipp/GetUserInfo.php
<?php

Obtain Access Token From Refresh Token

require __DIR__ . '/../bootstrap.php'; + +use PayPal\Auth\OpenId\PPOpenIdTokenInfo; +use PayPal\Auth\OpenId\PPOpenIdUserInfo;

To obtain User Info, you have to follow three steps in general. +First, you need to obtain user's consent to retrieve the information you want. +This is explained in the example "ObtainUserConsent.php".

Once you get the user's consent, the end result would be long lived refresh token. +This refresh token should be stored in a permanent storage for later use.

Lastly, when you need to retrieve the user information, you need to generate the short lived access token +to retreive the information. The short lived access token can be retrieved using the example shown in +"GenerateAccessTokenFromRefreshToken.php", or as shown below

You can retrieve the refresh token by executing ObtainUserConsent.php and store the refresh token

$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
lipp/ObtainUserConsent.php
<?php + +require __DIR__ . '/../bootstrap.php'; + +use PayPal\Auth\Openid\PPOpenIdSession; + +$baseUrl = getBaseUrl() . '/UserConsentRedirect.php?success=true';
+

The clientId is stored in the bootstrap file

//Get Authorization URL returns the redirect URL that could be used to get user's consent +$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
lipp/UserConsentRedirect.php
<?php + +require __DIR__ . '/../bootstrap.php'; + +use PayPal\Auth\Openid\PPOpenIdTokeninfo; +use PayPal\Exception\PPConnectionException; + +session_start();
+

PayPal would redirect the user to the redirect_uri mentioned when creating the consent URL. +The user would then able to retrieve the access token by getting the code, which is returned as a GET parameter.

if (isset($_GET['success']) && $_GET['success'] == 'true') { + + $code = $_GET['code']; + + try {

Obtain Authorization Code from Code, Client ID and Client Secret

$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();

Payer

@@ -31,22 +28,22 @@ payment approval/ cancellation.

$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true") ->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");

Payment

A Payment Resource; create one using -the above types and intent set to 'sale'

$payment = new Payment(); +the above types and intent set to 'sale'

$payment = new FuturePayment(); $payment->setIntent("authorize") ->setPayer($payer) ->setRedirectUrls($redirectUrls) ->setTransactions(array($transaction));

Get Refresh Token

-

You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.

authorization code from mobile sdk

$authorizationCode = 'EF4Ds2Wv1JbHiU_UuhR5v-ftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY';

correlation id from mobile sdk

$correlationId = '123123456'; +

You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.

authorization code from mobile sdk

$authorizationCode = 'EJfRuAqXEE95pdVMmOym_mftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY';

correlation id from mobile sdk

$correlationId = '123123456'; try {

Exchange authorization_code for long living refresh token. You should store -it in a database for later use

$refreshToken = $apiContext->getCredential()->getRefreshToken($apiContext->getConfig(), $authorizationCode);

Update the access token in apiContext

$apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refreshToken);

Create Future Payment

+it in a database for later use

$refreshToken = FuturePayment::getRefreshToken($authorizationCode, $apiContext);

Update the access token in apiContext

$payment->updateAccessToken($refreshToken, $apiContext);

Create Future Payment

Create a payment by calling the 'create' method passing it a valid apiContext. (See bootstrap.php for more on ApiContext) The return object contains the state and the url to which the buyer must be redirected to for payment approval -Please note that currently future payments works only with Paypal as a funding instrument.

$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;

Credit card token

Saved credit card id from a previous call to CreateCreditCard.php

$creditCardToken = new CreditCardToken(); -$creditCardToken->setCreditCardId('CARD-29H07236G1554552FKINPBHQ');

FundingInstrument

+$creditCardToken->setCreditCardId('CARD-17M96700G1952584EKRCTV5Y');

FundingInstrument

A resource representing a Payer's funding instrument. For stored credit card payments, set the CreditCardToken field on this object.

$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

//Execute the payment

(See bootstrap.php for more on ApiContext)

$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>"; }
\ No newline at end of file diff --git a/sample/doc/payments/GetPayment.html b/sample/doc/payments/GetPayment.html index 590721d..45ed0d6 100644 --- a/sample/doc/payments/GetPayment.html +++ b/sample/doc/payments/GetPayment.html @@ -8,7 +8,7 @@ payments list. API used: GET /v1/payments/payments

require __DIR__ . '/../bootstrap.php'; use PayPal\Api\Payment; -$paymentId = "PAY-0XL713371A312273YKE2GCNI";

Retrieve payment

+$paymentId = "PAY-2AH507590P6615624KRCTUSY";

Retrieve payment

Retrieve the payment object by calling the static get method on the Payment class by passing a valid diff --git a/sample/doc/vault/GetCreditCard.html b/sample/doc/vault/GetCreditCard.html index 2c0e662..0856d8a 100644 --- a/sample/doc/vault/GetCreditCard.html +++ b/sample/doc/vault/GetCreditCard.html @@ -5,7 +5,7 @@ API called: '/v1/vault/credit-card' The following code takes you through the process of retrieving a saved CreditCard

require __DIR__ . '/../bootstrap.php'; use PayPal\Api\CreditCard;

The cardId can be obtained from a previous save credit -card operation. Use $card->getId()

$cardId = "CARD-5AR29593TC404090HKIKN77Q"; +card operation. Use $card->getId()

$cardId = "CARD-44D10970C24287906KRCTWNI"; /// ### Retrieve card

(See bootstrap.php for more on ApiContext)

try { $card = CreditCard::get($cardId, $apiContext); diff --git a/sample/index.html b/sample/index.html index f65bc13..b80143f 100644 --- a/sample/index.html +++ b/sample/index.html @@ -360,6 +360,50 @@
+ +
+
+

Identity (LIPP)

+
+ + +
diff --git a/sample/invoice/CreateInvoice.php b/sample/invoice/CreateInvoice.php index 2df26fc..0cb4c0e 100644 --- a/sample/invoice/CreateInvoice.php +++ b/sample/invoice/CreateInvoice.php @@ -32,7 +32,7 @@ $invoice // A resource representing merchant information that can be // used to identify merchant $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/invoice/GetInvoice.php b/sample/invoice/GetInvoice.php index 1a48038..256f516 100644 --- a/sample/invoice/GetInvoice.php +++ b/sample/invoice/GetInvoice.php @@ -7,7 +7,7 @@ require __DIR__ . '/../bootstrap.php'; use PayPal\Api\Invoice; -$invoiceId = "INV2-9DRB-YTHU-2V9Q-7Q24"; +$invoiceId = "INV2-W4LC-6QS9-JZ62-VE4P"; // ### Retrieve Invoice // Retrieve the invoice object by calling the diff --git a/sample/invoice/RemindInvoice.php b/sample/invoice/RemindInvoice.php index 0ecb237..fa5796f 100644 --- a/sample/invoice/RemindInvoice.php +++ b/sample/invoice/RemindInvoice.php @@ -16,7 +16,7 @@ try { // 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); // ### Notification Object // This would send a notification to both merchant as well diff --git a/sample/invoice/SendInvoice.php b/sample/invoice/SendInvoice.php index 4740559..bc5f937 100644 --- a/sample/invoice/SendInvoice.php +++ b/sample/invoice/SendInvoice.php @@ -15,7 +15,7 @@ try { // on the Invoice class by passing a valid // Invoice ID // (See bootstrap.php for more on `ApiContext`) - $invoice = Invoice::get("INV2-9DRB-YTHU-2V9Q-7Q24", $apiContext); + $invoice = Invoice::get("INV2-W4LC-6QS9-JZ62-VE4P", $apiContext); // ### Send Invoice // Send a legitimate invoice to the payer diff --git a/sample/oauth/ObtainUserConsentFromRefreshToken.php b/sample/lipp/GenerateAccessTokenFromRefreshToken.php similarity index 62% rename from sample/oauth/ObtainUserConsentFromRefreshToken.php rename to sample/lipp/GenerateAccessTokenFromRefreshToken.php index 84d133e..649faac 100644 --- a/sample/oauth/ObtainUserConsentFromRefreshToken.php +++ b/sample/lipp/GenerateAccessTokenFromRefreshToken.php @@ -1,19 +1,18 @@ $refreshToken, - 'redirect_uri' => getBaseUrl() . '/UserConsentRedirect.php?success=true', - 'client_id' => $clientId, - 'client_secret' => $clientSecret -); try { - $tokenInfo = new \PayPal\Auth\Openid\PPOpenIdTokeninfo(); - $tokenInfo = $tokenInfo->createFromRefreshToken($params, $apiContext); + + $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()); diff --git a/sample/lipp/GetUserInfo.php b/sample/lipp/GetUserInfo.php new file mode 100644 index 0000000..34c74f8 --- /dev/null +++ b/sample/lipp/GetUserInfo.php @@ -0,0 +1,37 @@ +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)); diff --git a/sample/lipp/ObtainUserConsent.php b/sample/lipp/ObtainUserConsent.php new file mode 100644 index 0000000..9653e8b --- /dev/null +++ b/sample/lipp/ObtainUserConsent.php @@ -0,0 +1,22 @@ +Click Here to Obtain User Consent'); diff --git a/sample/lipp/UserConsentRedirect.php b/sample/lipp/UserConsentRedirect.php new file mode 100644 index 0000000..e046923 --- /dev/null +++ b/sample/lipp/UserConsentRedirect.php @@ -0,0 +1,28 @@ + $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); + +} diff --git a/sample/oauth/ObtainUserConsent.php b/sample/oauth/ObtainUserConsent.php deleted file mode 100644 index 84dc918..0000000 --- a/sample/oauth/ObtainUserConsent.php +++ /dev/null @@ -1,20 +0,0 @@ -/execute'. - -require __DIR__ . '/../bootstrap.php'; - -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() . '/UserConsentRedirect.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); - } - - print_result("Obtained Access Token", "Access Token", $accessToken->getAccessToken(), $accessToken); - -} diff --git a/sample/payments/CreateFuturePayment.php b/sample/payments/CreateFuturePayment.php index 66e6880..674caf4 100644 --- a/sample/payments/CreateFuturePayment.php +++ b/sample/payments/CreateFuturePayment.php @@ -7,11 +7,8 @@ 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(); @@ -50,7 +47,7 @@ $redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true") // ### Payment // A Payment Resource; create one using // the above types and intent set to 'sale' -$payment = new Payment(); +$payment = new FuturePayment(); $payment->setIntent("authorize") ->setPayer($payer) ->setRedirectUrls($redirectUrls) @@ -60,7 +57,7 @@ $payment->setIntent("authorize") // You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk. // authorization code from mobile sdk -$authorizationCode = 'EF4Ds2Wv1JbHiU_UuhR5v-ftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY'; +$authorizationCode = 'EJfRuAqXEE95pdVMmOym_mftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY'; // correlation id from mobile sdk $correlationId = '123123456'; @@ -68,10 +65,10 @@ $correlationId = '123123456'; try { // Exchange authorization_code for long living refresh token. You should store // it in a database for later use - $refreshToken = $apiContext->getCredential()->getRefreshToken($apiContext->getConfig(), $authorizationCode); + $refreshToken = FuturePayment::getRefreshToken($authorizationCode, $apiContext); // Update the access token in apiContext - $apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refreshToken); + $payment->updateAccessToken($refreshToken, $apiContext); // ### Create Future Payment // Create a payment by calling the 'create' method @@ -80,7 +77,7 @@ try { // The return object contains the state and the // url to which the buyer must be redirected to // for payment approval - // Please note that currently future payments works only with Paypal as a funding instrument. + // Please note that currently future payments works only with PayPal as a funding instrument. $payment->create($apiContext, $correlationId); } catch (PayPal\Exception\PPConnectionException $ex) { diff --git a/sample/payments/CreatePayment.php b/sample/payments/CreatePayment.php index 6dc0ad7..9cfa1cb 100644 --- a/sample/payments/CreatePayment.php +++ b/sample/payments/CreatePayment.php @@ -1,129 +1,129 @@ -setType("visa") - ->setNumber("4417119669820331") - ->setExpireMonth("11") - ->setExpireYear("2019") - ->setCvv2("012") - ->setFirstName("Joe") - ->setLastName("Shopper"); - -// ### FundingInstrument -// A resource representing a Payer's funding instrument. -// For direct credit card payments, set the CreditCard -// field on this object. -$fi = new FundingInstrument(); -$fi->setCreditCard($card); - -// ### Payer -// A resource representing a Payer that funds a payment -// For direct credit card payments, set payment method -// to 'credit_card' and add an array of funding instruments. -$payer = new Payer(); -$payer->setPaymentMethod("credit_card") - ->setFundingInstruments(array($fi)); - -// ### Itemized information -// (Optional) Lets you specify item wise -// information -$item1 = new Item(); -$item1->setName('Ground Coffee 40 oz') - ->setDescription('Ground Coffee 40 oz') - ->setCurrency('USD') - ->setQuantity(1) - ->setTax('0.30') - ->setPrice('7.50'); -$item2 = new Item(); -$item2->setName('Granola bars') - ->setDescription('Granola Bars with Peanuts') - ->setCurrency('USD') - ->setQuantity(5) - ->setTax('0.20') - ->setPrice('2.00'); - -$itemList = new ItemList(); -$itemList->setItems(array($item1, $item2)); - -// ### Additional payment details -// Use this optional field to set additional -// payment information such as tax, shipping -// charges etc. -$details = new Details(); -$details->setShipping('1.20') - ->setTax('1.30') - ->setSubtotal('17.50'); - -// ### Amount -// Lets you specify a payment amount. -// You can also specify additional details -// such as shipping, tax. -$amount = new Amount(); -$amount->setCurrency("USD") - ->setTotal("20.00") - ->setDetails($details); - -// ### Transaction -// A transaction defines the contract of a -// payment - what is the payment for and who -// is fulfilling it. -$transaction = new Transaction(); -$transaction->setAmount($amount) - ->setItemList($itemList) - ->setDescription("Payment description"); - -// ### Payment -// A Payment Resource; create one using -// the above types and intent set to sale 'sale' -$payment = new Payment(); -$payment->setIntent("sale") - ->setPayer($payer) - ->setTransactions(array($transaction)); - -// ### Create Payment -// Create a payment by calling the payment->create() method -// with a valid ApiContext (See bootstrap.php for more on `ApiContext`) -// The return object contains the state. -try { - $payment->create($apiContext); -} catch (PayPal\Exception\PPConnectionException $ex) { - echo "Exception: " . $ex->getMessage() . PHP_EOL; - var_dump($ex->getData()); - exit(1); -} -?> - - - Direct Credit card payments - - -
- Created payment: - getId();?> -
-
toJSON(JSON_PRETTY_PRINT);?>
- Back - - \ No newline at end of file +setType("visa") + ->setNumber("4417119669820331") + ->setExpireMonth("11") + ->setExpireYear("2019") + ->setCvv2("012") + ->setFirstName("Joe") + ->setLastName("Shopper"); + +// ### FundingInstrument +// A resource representing a Payer's funding instrument. +// For direct credit card payments, set the CreditCard +// field on this object. +$fi = new FundingInstrument(); +$fi->setCreditCard($card); + +// ### Payer +// A resource representing a Payer that funds a payment +// For direct credit card payments, set payment method +// to 'credit_card' and add an array of funding instruments. +$payer = new Payer(); +$payer->setPaymentMethod("credit_card") + ->setFundingInstruments(array($fi)); + +// ### Itemized information +// (Optional) Lets you specify item wise +// information +$item1 = new Item(); +$item1->setName('Ground Coffee 40 oz') + ->setDescription('Ground Coffee 40 oz') + ->setCurrency('USD') + ->setQuantity(1) + ->setTax('0.30') + ->setPrice('7.50'); +$item2 = new Item(); +$item2->setName('Granola bars') + ->setDescription('Granola Bars with Peanuts') + ->setCurrency('USD') + ->setQuantity(5) + ->setTax('0.20') + ->setPrice('2.00'); + +$itemList = new ItemList(); +$itemList->setItems(array($item1, $item2)); + +// ### Additional payment details +// Use this optional field to set additional +// payment information such as tax, shipping +// charges etc. +$details = new Details(); +$details->setShipping('1.20') + ->setTax('1.30') + ->setSubtotal('17.50'); + +// ### Amount +// Lets you specify a payment amount. +// You can also specify additional details +// such as shipping, tax. +$amount = new Amount(); +$amount->setCurrency("USD") + ->setTotal("20.00") + ->setDetails($details); + +// ### Transaction +// A transaction defines the contract of a +// payment - what is the payment for and who +// is fulfilling it. +$transaction = new Transaction(); +$transaction->setAmount($amount) + ->setItemList($itemList) + ->setDescription("Payment description"); + +// ### Payment +// A Payment Resource; create one using +// the above types and intent set to sale 'sale' +$payment = new Payment(); +$payment->setIntent("sale") + ->setPayer($payer) + ->setTransactions(array($transaction)); + +// ### Create Payment +// Create a payment by calling the payment->create() method +// with a valid ApiContext (See bootstrap.php for more on `ApiContext`) +// The return object contains the state. +try { + $payment->create($apiContext); +} catch (PayPal\Exception\PPConnectionException $ex) { + echo "Exception: " . $ex->getMessage() . PHP_EOL; + var_dump($ex->getData()); + exit(1); +} +?> + + + Direct Credit card payments + + +
+ Created payment: + getId();?> +
+
toJSON(JSON_PRETTY_PRINT);?>
+ Back + + diff --git a/sample/payments/CreatePaymentUsingPayPal.php b/sample/payments/CreatePaymentUsingPayPal.php index b8fcae0..712c629 100644 --- a/sample/payments/CreatePaymentUsingPayPal.php +++ b/sample/payments/CreatePaymentUsingPayPal.php @@ -1,125 +1,125 @@ -setPaymentMethod("paypal"); - -// ### Itemized information -// (Optional) Lets you specify item wise -// information -$item1 = new Item(); -$item1->setName('Ground Coffee 40 oz') - ->setCurrency('USD') - ->setQuantity(1) - ->setPrice('7.50'); -$item2 = new Item(); -$item2->setName('Granola bars') - ->setCurrency('USD') - ->setQuantity(5) - ->setPrice('2.00'); - -$itemList = new ItemList(); -$itemList->setItems(array($item1, $item2)); - -// ### Additional payment details -// Use this optional field to set additional -// payment information such as tax, shipping -// charges etc. -$details = new Details(); -$details->setShipping('1.20') - ->setTax('1.30') - ->setSubtotal('17.50'); - -// ### Amount -// Lets you specify a payment amount. -// You can also specify additional details -// such as shipping, tax. -$amount = new Amount(); -$amount->setCurrency("USD") - ->setTotal("20.00") - ->setDetails($details); - -// ### Transaction -// A transaction defines the contract of a -// payment - what is the payment for and who -// is fulfilling it. -$transaction = new Transaction(); -$transaction->setAmount($amount) - ->setItemList($itemList) - ->setDescription("Payment description"); - -// ### Redirect urls -// Set the urls that the buyer must be redirected to after -// payment approval/ cancellation. -$baseUrl = getBaseUrl(); -$redirectUrls = new RedirectUrls(); -$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true") - ->setCancelUrl("$baseUrl/ExecutePayment.php?success=false"); - -// ### Payment -// A Payment Resource; create one using -// the above types and intent set to 'sale' -$payment = new Payment(); -$payment->setIntent("sale") - ->setPayer($payer) - ->setRedirectUrls($redirectUrls) - ->setTransactions(array($transaction)); - -// ### Create Payment -// Create a payment by calling the 'create' method -// passing it a valid apiContext. -// (See bootstrap.php for more on `ApiContext`) -// The return object contains the state and the -// url to which the buyer must be redirected to -// for payment approval -try { - $payment->create($apiContext); -} catch (PayPal\Exception\PPConnectionException $ex) { - echo "Exception: " . $ex->getMessage() . PHP_EOL; - var_dump($ex->getData()); - exit(1); -} - -// ### Get redirect url -// The API response provides the url that you must redirect -// the buyer to. Retrieve the url from the $payment->getLinks() -// method -foreach($payment->getLinks() as $link) { - if($link->getRel() == 'approval_url') { - $redirectUrl = $link->getHref(); - break; - } -} - -// ### Redirect buyer to PayPal website -// Save the payment id so that you can 'complete' the payment -// once the buyer approves the payment and is redirected -// back to your website. -// -// It is not a great idea to store the payment id -// in the session. In a real world app, you may want to -// store the payment id in a database. -$_SESSION['paymentId'] = $payment->getId(); -if(isset($redirectUrl)) { - header("Location: $redirectUrl"); - exit; -} +setPaymentMethod("paypal"); + +// ### Itemized information +// (Optional) Lets you specify item wise +// information +$item1 = new Item(); +$item1->setName('Ground Coffee 40 oz') + ->setCurrency('USD') + ->setQuantity(1) + ->setPrice('7.50'); +$item2 = new Item(); +$item2->setName('Granola bars') + ->setCurrency('USD') + ->setQuantity(5) + ->setPrice('2.00'); + +$itemList = new ItemList(); +$itemList->setItems(array($item1, $item2)); + +// ### Additional payment details +// Use this optional field to set additional +// payment information such as tax, shipping +// charges etc. +$details = new Details(); +$details->setShipping('1.20') + ->setTax('1.30') + ->setSubtotal('17.50'); + +// ### Amount +// Lets you specify a payment amount. +// You can also specify additional details +// such as shipping, tax. +$amount = new Amount(); +$amount->setCurrency("USD") + ->setTotal("20.00") + ->setDetails($details); + +// ### Transaction +// A transaction defines the contract of a +// payment - what is the payment for and who +// is fulfilling it. +$transaction = new Transaction(); +$transaction->setAmount($amount) + ->setItemList($itemList) + ->setDescription("Payment description"); + +// ### Redirect urls +// Set the urls that the buyer must be redirected to after +// payment approval/ cancellation. +$baseUrl = getBaseUrl(); +$redirectUrls = new RedirectUrls(); +$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true") + ->setCancelUrl("$baseUrl/ExecutePayment.php?success=false"); + +// ### Payment +// A Payment Resource; create one using +// the above types and intent set to 'sale' +$payment = new Payment(); +$payment->setIntent("sale") + ->setPayer($payer) + ->setRedirectUrls($redirectUrls) + ->setTransactions(array($transaction)); + +// ### Create Payment +// Create a payment by calling the 'create' method +// passing it a valid apiContext. +// (See bootstrap.php for more on `ApiContext`) +// The return object contains the state and the +// url to which the buyer must be redirected to +// for payment approval +try { + $payment->create($apiContext); +} catch (PayPal\Exception\PPConnectionException $ex) { + echo "Exception: " . $ex->getMessage() . PHP_EOL; + var_dump($ex->getData()); + exit(1); +} + +// ### Get redirect url +// The API response provides the url that you must redirect +// the buyer to. Retrieve the url from the $payment->getLinks() +// method +foreach($payment->getLinks() as $link) { + if($link->getRel() == 'approval_url') { + $redirectUrl = $link->getHref(); + break; + } +} + +// ### Redirect buyer to PayPal website +// Save the payment id so that you can 'complete' the payment +// once the buyer approves the payment and is redirected +// back to your website. +// +// It is not a great idea to store the payment id +// in the session. In a real world app, you may want to +// store the payment id in a database. +$_SESSION['paymentId'] = $payment->getId(); +if(isset($redirectUrl)) { + header("Location: $redirectUrl"); + exit; +} diff --git a/sample/payments/CreatePaymentUsingSavedCard.php b/sample/payments/CreatePaymentUsingSavedCard.php index 7c682ed..344401b 100644 --- a/sample/payments/CreatePaymentUsingSavedCard.php +++ b/sample/payments/CreatePaymentUsingSavedCard.php @@ -1,117 +1,117 @@ -setCreditCardId('CARD-29H07236G1554552FKINPBHQ'); - -// ### FundingInstrument -// A resource representing a Payer's funding instrument. -// For stored credit card payments, set the CreditCardToken -// field on this object. -$fi = new FundingInstrument(); -$fi->setCreditCardToken($creditCardToken); - -// ### Payer -// A resource representing a Payer that funds a payment -// For stored credit card payments, set payment method -// to 'credit_card'. -$payer = new Payer(); -$payer->setPaymentMethod("credit_card") - ->setFundingInstruments(array($fi)); - -// ### Itemized information -// (Optional) Lets you specify item wise -// information -$item1 = new Item(); -$item1->setName('Ground Coffee 40 oz') - ->setCurrency('USD') - ->setQuantity(1) - ->setPrice('7.50'); -$item2 = new Item(); -$item2->setName('Granola bars') - ->setCurrency('USD') - ->setQuantity(5) - ->setPrice('2.00'); - -$itemList = new ItemList(); -$itemList->setItems(array($item1, $item2)); - -// ### Additional payment details -// Use this optional field to set additional -// payment information such as tax, shipping -// charges etc. -$details = new Details(); -$details->setShipping('1.20') - ->setTax('1.30') - ->setSubtotal('17.50'); - -// ### Amount -// Lets you specify a payment amount. -// You can also specify additional details -// such as shipping, tax. -$amount = new Amount(); -$amount->setCurrency("USD") - ->setTotal("20.00") - ->setDetails($details); - -// ### Transaction -// A transaction defines the contract of a -// payment - what is the payment for and who -// is fulfilling it. -$transaction = new Transaction(); -$transaction->setAmount($amount) - ->setItemList($itemList) - ->setDescription("Payment description"); - -// ### Payment -// A Payment Resource; create one using -// the above types and intent set to 'sale' -$payment = new Payment(); -$payment->setIntent("sale") - ->setPayer($payer) - ->setTransactions(array($transaction)); - -// ###Create Payment -// Create a payment by calling the 'create' method -// passing it a valid apiContext. -// (See bootstrap.php for more on `ApiContext`) -// The return object contains the state. -try { - $payment->create($apiContext); -} catch (PayPal\Exception\PPConnectionException $ex) { - echo "Exception: " . $ex->getMessage() . PHP_EOL; - var_dump($ex->getData()); - exit(1); -} -?> - - - Saved Credit card payments - - -
- Created payment: - getId();?> -
-
toJSON(JSON_PRETTY_PRINT);?>
- Back - - +setCreditCardId('CARD-17M96700G1952584EKRCTV5Y'); + +// ### FundingInstrument +// A resource representing a Payer's funding instrument. +// For stored credit card payments, set the CreditCardToken +// field on this object. +$fi = new FundingInstrument(); +$fi->setCreditCardToken($creditCardToken); + +// ### Payer +// A resource representing a Payer that funds a payment +// For stored credit card payments, set payment method +// to 'credit_card'. +$payer = new Payer(); +$payer->setPaymentMethod("credit_card") + ->setFundingInstruments(array($fi)); + +// ### Itemized information +// (Optional) Lets you specify item wise +// information +$item1 = new Item(); +$item1->setName('Ground Coffee 40 oz') + ->setCurrency('USD') + ->setQuantity(1) + ->setPrice('7.50'); +$item2 = new Item(); +$item2->setName('Granola bars') + ->setCurrency('USD') + ->setQuantity(5) + ->setPrice('2.00'); + +$itemList = new ItemList(); +$itemList->setItems(array($item1, $item2)); + +// ### Additional payment details +// Use this optional field to set additional +// payment information such as tax, shipping +// charges etc. +$details = new Details(); +$details->setShipping('1.20') + ->setTax('1.30') + ->setSubtotal('17.50'); + +// ### Amount +// Lets you specify a payment amount. +// You can also specify additional details +// such as shipping, tax. +$amount = new Amount(); +$amount->setCurrency("USD") + ->setTotal("20.00") + ->setDetails($details); + +// ### Transaction +// A transaction defines the contract of a +// payment - what is the payment for and who +// is fulfilling it. +$transaction = new Transaction(); +$transaction->setAmount($amount) + ->setItemList($itemList) + ->setDescription("Payment description"); + +// ### Payment +// A Payment Resource; create one using +// the above types and intent set to 'sale' +$payment = new Payment(); +$payment->setIntent("sale") + ->setPayer($payer) + ->setTransactions(array($transaction)); + +// ###Create Payment +// Create a payment by calling the 'create' method +// passing it a valid apiContext. +// (See bootstrap.php for more on `ApiContext`) +// The return object contains the state. +try { + $payment->create($apiContext); +} catch (PayPal\Exception\PPConnectionException $ex) { + echo "Exception: " . $ex->getMessage() . PHP_EOL; + var_dump($ex->getData()); + exit(1); +} +?> + + + Saved Credit card payments + + +
+ Created payment: + getId();?> +
+
toJSON(JSON_PRETTY_PRINT);?>
+ Back + + diff --git a/sample/payments/ExecutePayment.php b/sample/payments/ExecutePayment.php index e3b9e65..dba78f5 100644 --- a/sample/payments/ExecutePayment.php +++ b/sample/payments/ExecutePayment.php @@ -1,40 +1,42 @@ -/execute'. - -require __DIR__ . '/../bootstrap.php'; -use PayPal\Api\ExecutePayment; -use PayPal\Api\Payment; -use PayPal\Api\PaymentExecution; -session_start(); -if(isset($_GET['success']) && $_GET['success'] == 'true') { - - // Get the payment Object by passing paymentId - // payment id was previously stored in session in - // CreatePaymentUsingPayPal.php - $paymentId = $_SESSION['paymentId']; - $payment = Payment::get($paymentId, $apiContext); - - // PaymentExecution object includes information necessary - // to execute a PayPal account payment. - // The payer_id is added to the request query parameters - // when the user is redirected from paypal back to your site - $execution = new PaymentExecution(); - $execution->setPayerId($_GET['PayerID']); - - //Execute the payment - // (See bootstrap.php for more on `ApiContext`) - $result = $payment->execute($execution, $apiContext); - - echo "
";
-	echo $result->toJSON(JSON_PRETTY_PRINT);
-	echo "
Back"; - -} else { - echo "User cancelled payment."; -} +/execute'. + +require __DIR__ . '/../bootstrap.php'; +use PayPal\Api\ExecutePayment; +use PayPal\Api\Payment; +use PayPal\Api\PaymentExecution; +session_start(); +if(isset($_GET['success']) && $_GET['success'] == 'true') { + + // Get the payment Object by passing paymentId + // payment id was previously stored in session in + // CreatePaymentUsingPayPal.php + $paymentId = $_SESSION['paymentId']; + $payment = Payment::get($paymentId, $apiContext); + + // PaymentExecution object includes information necessary + // to execute a PayPal account payment. + // The payer_id is added to the request query parameters + // when the user is redirected from paypal back to your site + $execution = new PaymentExecution(); + $execution->setPayerId($_GET['PayerID']); + + //Execute the payment + // (See bootstrap.php for more on `ApiContext`) + $result = $payment->execute($execution, $apiContext); + + echo "
";
+	echo $result->toJSON(JSON_PRETTY_PRINT);
+	echo "
Back"; + +} else { + echo "

"; + echo "User cancelled payment."; + echo "

Back"; +} diff --git a/sample/payments/GetPayment.php b/sample/payments/GetPayment.php index 9eef28c..5d81d93 100644 --- a/sample/payments/GetPayment.php +++ b/sample/payments/GetPayment.php @@ -1,39 +1,39 @@ -getMessage() . PHP_EOL; - var_dump($ex->getData()); - exit(1); -} -?> - - - Lookup a payment - - -
Retrieving Payment ID:
-
toJSON(JSON_PRETTY_PRINT);?>
- Back - - +getMessage() . PHP_EOL; + var_dump($ex->getData()); + exit(1); +} +?> + + + Lookup a payment + + +
Retrieving Payment ID:
+
toJSON(JSON_PRETTY_PRINT);?>
+ Back + + diff --git a/sample/sdk_config.ini b/sample/sdk_config.ini index fb9874b..e3bd63e 100644 --- a/sample/sdk_config.ini +++ b/sample/sdk_config.ini @@ -1,4 +1,6 @@ - +[Account] +acct1.ClientId = AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS +acct1.ClientSecret = EGnHDxD_qRPdaLdZz8iCr8N7_MzF-YHPTkjs6NKYQvQSBngp4PTTVWkPZRbL ## This is an example configuration file for the SDK. ## The sample scripts configure the SDK dynamically diff --git a/sample/vault/GetCreditCard.php b/sample/vault/GetCreditCard.php index fb57ac9..afdda0f 100644 --- a/sample/vault/GetCreditCard.php +++ b/sample/vault/GetCreditCard.php @@ -11,7 +11,7 @@ use PayPal\Api\CreditCard; // The cardId can be obtained from a previous save credit // card operation. Use $card->getId() -$cardId = "CARD-5AR29593TC404090HKIKN77Q"; +$cardId = "CARD-44D10970C24287906KRCTWNI"; /// ### Retrieve card // (See bootstrap.php for more on `ApiContext`)