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
This commit is contained in:
japatel
2014-10-20 12:04:41 -05:00
parent dcc147ac7e
commit 84660cbb2a
42 changed files with 1156 additions and 789 deletions

View File

@@ -21,7 +21,8 @@ class FuturePayment extends Payment
* @param $correlationId * @param $correlationId
* @return $this * @return $this
*/ */
public function create($apiContext = null, $correlationId = null) { public function create($apiContext = null, $correlationId = null)
{
if ($apiContext == null) { if ($apiContext == null) {
$apiContext = new ApiContext(self::$credential); $apiContext = new ApiContext(self::$credential);
} }
@@ -45,4 +46,31 @@ class FuturePayment extends Payment
return $this; 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);
}
} }

View File

@@ -1,236 +1,271 @@
<?php <?php
namespace PayPal\Auth; namespace PayPal\Auth;
use PayPal\Common\PPUserAgent; use PayPal\Common\PPUserAgent;
use PayPal\Core\PPConstants; use PayPal\Common\ResourceModel;
use PayPal\Core\PPHttpConfig; use PayPal\Core\PPConstants;
use PayPal\Core\PPHttpConnection; use PayPal\Core\PPHttpConfig;
use PayPal\Core\PPLoggingManager; use PayPal\Core\PPHttpConnection;
use PayPal\Exception\PPConfigurationException; use PayPal\Core\PPLoggingManager;
use PayPal\Rest\RestHandler; use PayPal\Exception\PPConfigurationException;
use PayPal\Rest\RestHandler;
/**
* Class OAuthTokenCredential /**
*/ * Class OAuthTokenCredential
class OAuthTokenCredential */
{ class OAuthTokenCredential extends ResourceModel
/** {
* Private Variable /**
* * Private Variable
* @var int $expiryBufferTime *
*/ * @var int $expiryBufferTime
private static $expiryBufferTime = 120; */
private static $expiryBufferTime = 120;
/**
* Private Variable /**
* * Private Variable
* @var \PayPal\Core\PPLoggingManager $logger *
*/ * @var \PayPal\Core\PPLoggingManager $logger
private $logger; */
private $logger;
/**
* Client ID as obtained from the developer portal /**
* * Client ID as obtained from the developer portal
* @var string $clientId *
*/ * @var string $clientId
private $clientId; */
private $clientId;
/**
* Client secret as obtained from the developer portal /**
* * Client secret as obtained from the developer portal
* @var string $clientSecret *
*/ * @var string $clientSecret
private $clientSecret; */
private $clientSecret;
/**
* Generated Access Token /**
* * Generated Access Token
* @var string $accessToken *
*/ * @var string $accessToken
private $accessToken; */
private $accessToken;
/**
* Seconds for with access token is valid /**
* * Seconds for with access token is valid
* @var $tokenExpiresIn *
*/ * @var $tokenExpiresIn
private $tokenExpiresIn; */
private $tokenExpiresIn;
/**
* Last time (in milliseconds) when access token was generated /**
* * Last time (in milliseconds) when access token was generated
* @var $tokenCreateTime *
*/ * @var $tokenCreateTime
private $tokenCreateTime; */
private $tokenCreateTime;
/**
* Construct /**
* * Construct
* @param string $clientId client id obtained from the developer portal *
* @param string $clientSecret client secret obtained from the developer portal * @param string $clientId client id obtained from the developer portal
*/ * @param string $clientSecret client secret obtained from the developer portal
public function __construct($clientId, $clientSecret) */
{ public function __construct($clientId, $clientSecret)
$this->clientId = $clientId; {
$this->clientSecret = $clientSecret; $this->clientId = $clientId;
$this->logger = PPLoggingManager::getInstance(__CLASS__); $this->clientSecret = $clientSecret;
} $this->logger = PPLoggingManager::getInstance(__CLASS__);
}
/**
* Get AccessToken /**
* * Get Client ID
* @param $config *
* * @return string
* @return null|string */
*/ public function getClientId()
public function getAccessToken($config) {
{ return $this->clientId;
// 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 * Get Client Secret
// retrieved and subsequently used *
if ( * @return string
$this->accessToken != null && */
(time() - $this->tokenCreateTime) > ($this->tokenExpiresIn - self::$expiryBufferTime) public function getClientSecret()
) { {
$this->accessToken = null; return $this->clientSecret;
} }
// If accessToken is Null, obtain a new token /**
if ($this->accessToken == null) { * Get AccessToken
$this->updateAccessToken($config); *
} * @param $config
*
return $this->accessToken; * @return null|string
} */
public function getAccessToken($config)
/** {
* Get a Refresh Token from Authorization Code // Check if Access Token is not null and has not expired.
* // The API returns expiry time as a relative time unit
* @param $config // We use a buffer time when checking for token expiry to account
* @param $authorizationCode // for API call delays and any delay between the time the token is
* @return string|null // retrieved and subsequently used
*/ if (
public function getRefreshToken($config, $authorizationCode) //Which comes from Mobile. $this->accessToken != null &&
{ (time() - $this->tokenCreateTime) > ($this->tokenExpiresIn - self::$expiryBufferTime)
$payload = ) {
"grant_type=authorization_code&code=". $this->accessToken = null;
$authorizationCode. }
"&redirect_uri=urn:ietf:wg:oauth:2.0:oob&response_type=token";
$jsonResponse = $this->getToken($config, $payload); // If accessToken is Null, obtain a new token
if ($this->accessToken == null) {
if ($jsonResponse != null && isset($jsonResponse["refresh_token"])) { $this->updateAccessToken($config);
return $jsonResponse['refresh_token']; }
}
} return $this->accessToken;
}
/**
* Updates Access Token based on given input /**
* * Get a Refresh Token from Authorization Code
* @param $config *
* @param string|null $refreshToken * @param $config
* @return string * @param $authorizationCode
*/ * @param array $params optional arrays to override defaults
public function updateAccessToken($config, $refreshToken = null) * @return string|null
{ */
$this->generateAccessToken($config, $refreshToken); public function getRefreshToken($config, $authorizationCode = null, $params = array())
return $this->accessToken; {
} static $allowedParams = array(
'grant_type' => 'authorization_code',
/** 'code' => 1,
* Retrieves the token based on the input configuration 'redirect_uri' => 'urn:ietf:wg:oauth:2.0:oob',
* 'response_type' => 'token'
* @param array $config );
* @param string $payload
* @return mixed $params = is_array($params) ? $params : array();
* @throws PPConfigurationException if ($authorizationCode) {
* @throws \PayPal\Exception\PPConnectionException //Override the authorizationCode if value is explicitly set
*/ $params['code'] = $authorizationCode;
private function getToken($config, $payload) }
{ $payload = http_build_query(array_merge($allowedParams, array_intersect_key($params, $allowedParams)));
$base64ClientID = base64_encode($this->clientId . ":" . $this->clientSecret);
$headers = array( $response = $this->getToken($config, $this->clientId, $this->clientSecret, $payload);
"User-Agent" => PPUserAgent::getValue(RestHandler::$sdkName, RestHandler::$sdkVersion),
"Authorization" => "Basic " . $base64ClientID, if ($response != null && isset($response["refresh_token"])) {
"Accept" => "*/*" return $response['refresh_token'];
); }
}
$httpConfiguration = $this->getOAuthHttpConfiguration($config);
$httpConfiguration->setHeaders($headers); /**
* Updates Access Token based on given input
$connection = new PPHttpConnection($httpConfiguration, $config); *
$res = $connection->execute($payload); * @param $config
$jsonResponse = json_decode($res, true); * @param string|null $refreshToken
* @return string
if ($jsonResponse == null || !isset($jsonResponse["access_token"]) || !isset($jsonResponse["expires_in"])) { */
$this->accessToken = null; public function updateAccessToken($config, $refreshToken = null)
$this->tokenExpiresIn = null; {
$this->logger->warning( $this->generateAccessToken($config, $refreshToken);
"Could not generate new Access token. Invalid response from server: " . $jsonResponse return $this->accessToken;
); }
} else {
$this->accessToken = $jsonResponse["access_token"]; /**
$this->tokenExpiresIn = $jsonResponse["expires_in"]; * Retrieves the token based on the input configuration
} *
$this->tokenCreateTime = time(); * @param array $config
return $jsonResponse; * @param string $payload
} * @return mixed
* @throws PPConfigurationException
* @throws \PayPal\Exception\PPConnectionException
/** */
* Generates a new access token private function getToken($config, $clientId, $clientSecret, $payload)
* {
* @param array $config $base64ClientID = base64_encode($clientId . ":" . $clientSecret);
* @return null $headers = array(
*/ "User-Agent" => PPUserAgent::getValue(RestHandler::$sdkName, RestHandler::$sdkVersion),
private function generateAccessToken($config, $refreshToken = null) "Authorization" => "Basic " . $base64ClientID,
{ "Accept" => "*/*"
$payload = "grant_type=client_credentials"; );
if ($refreshToken != null) {
// If the refresh token is provided, it would get access token using refresh token $httpConfiguration = self::getOAuthHttpConfiguration($config);
// Used for Future Payments $httpConfiguration->setHeaders($headers);
$payload = "grant_type=refresh_token&refresh_token=$refreshToken";
} $connection = new PPHttpConnection($httpConfiguration, $config);
$this->getToken($config, $payload); $res = $connection->execute($payload);
$response = json_decode($res, true);
return $this->accessToken;
} return $response;
}
/**
* Get HttpConfiguration object for OAuth API
* /**
* @param array $config * Generates a new access token
* *
* @return PPHttpConfig * @param array $config
* @throws \PayPal\Exception\PPConfigurationException * @return null
*/ */
private function getOAuthHttpConfiguration($config) private function generateAccessToken($config, $refreshToken = null)
{ {
if (isset($config['oauth.EndPoint'])) { $params = array('grant_type' => 'client_credentials');
$baseEndpoint = $config['oauth.EndPoint']; if ($refreshToken != null) {
} else if (isset($config['service.EndPoint'])) { // If the refresh token is provided, it would get access token using refresh token
$baseEndpoint = $config['service.EndPoint']; // Used for Future Payments
} else if (isset($config['mode'])) { $params['grant_type'] = 'refresh_token';
switch (strtoupper($config['mode'])) { $params['refresh_token'] = $refreshToken;
case 'SANDBOX': }
$baseEndpoint = PPConstants::REST_SANDBOX_ENDPOINT; $payload = http_build_query($params);
break; $response = $this->getToken($config, $this->clientId, $this->clientSecret, $payload);
case 'LIVE':
$baseEndpoint = PPConstants::REST_LIVE_ENDPOINT; if ($response == null || !isset($response["access_token"]) || !isset($response["expires_in"])) {
break; $this->accessToken = null;
default: $this->tokenExpiresIn = null;
throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live'); $this->logger->warning(
} "Could not generate new Access token. Invalid response from server: " . $response
} else { );
throw new PPConfigurationException( } else {
'You must set one of service.endpoint or mode parameters in your configuration' $this->accessToken = $response["access_token"];
); $this->tokenExpiresIn = $response["expires_in"];
} }
$this->tokenCreateTime = time();
$baseEndpoint = rtrim(trim($baseEndpoint), '/');
return $this->accessToken;
return new PPHttpConfig($baseEndpoint . "/v1/oauth2/token", "POST"); }
}
} /**
* 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");
}
}

View File

@@ -28,6 +28,9 @@ class PPOpenIdSession
if ($apiContext->get($clientId)) { if ($apiContext->get($clientId)) {
$clientId = $apiContext->get($clientId); $clientId = $apiContext->get($clientId);
} }
$clientId = $clientId ? $clientId : $apiContext->getCredential()->getClientId();
$scope = count($scope) != 0 ? $scope : array('openid', 'profile', 'address', 'email', 'phone', $scope = count($scope) != 0 ? $scope : array('openid', 'profile', 'address', 'email', 'phone',
'https://uri.paypal.com/services/paypalattributes', 'https://uri.paypal.com/services/expresscheckout'); 'https://uri.paypal.com/services/paypalattributes', 'https://uri.paypal.com/services/expresscheckout');
if (!in_array('openid', $scope)) { if (!in_array('openid', $scope)) {

View File

@@ -164,6 +164,7 @@ class PPOpenIdTokeninfo extends ResourceModel
if (!array_key_exists('grant_type', $params)) { if (!array_key_exists('grant_type', $params)) {
$params['grant_type'] = 'authorization_code'; $params['grant_type'] = 'authorization_code';
} }
$apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
if (sizeof($apiContext->get($clientId)) > 0) { if (sizeof($apiContext->get($clientId)) > 0) {
$clientId = $apiContext->get($clientId); $clientId = $apiContext->get($clientId);
@@ -172,6 +173,10 @@ class PPOpenIdTokeninfo extends ResourceModel
if (sizeof($apiContext->get($clientSecret)) > 0) { if (sizeof($apiContext->get($clientSecret)) > 0) {
$clientSecret = $apiContext->get($clientSecret); $clientSecret = $apiContext->get($clientSecret);
} }
$clientId = $clientId ? $clientId : $apiContext->getCredential()->getClientId();
$clientSecret = $clientSecret ? $clientSecret : $apiContext->getCredential()->getClientSecret();
$json = self::executeCall( $json = self::executeCall(
"/v1/identity/openidconnect/tokenservice", "/v1/identity/openidconnect/tokenservice",
"POST", "POST",
@@ -205,6 +210,7 @@ class PPOpenIdTokeninfo extends ResourceModel
public function createFromRefreshToken($params, $apiContext = null) public function createFromRefreshToken($params, $apiContext = null)
{ {
static $allowedParams = array('grant_type' => 1, 'refresh_token' => 1, 'scope' => 1); 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)) { if (!array_key_exists('grant_type', $params)) {
$params['grant_type'] = 'refresh_token'; $params['grant_type'] = 'refresh_token';
@@ -213,13 +219,16 @@ class PPOpenIdTokeninfo extends ResourceModel
$params['refresh_token'] = $this->getRefreshToken(); $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( $json = self::executeCall(
"/v1/identity/openidconnect/tokenservice", "/v1/identity/openidconnect/tokenservice",
"POST", "POST",
http_build_query(array_intersect_key($params, $allowedParams)), http_build_query(array_intersect_key($params, $allowedParams)),
array( array(
'Content-Type' => 'application/x-www-form-urlencoded', 'Content-Type' => 'application/x-www-form-urlencoded',
'Authorization' => 'Basic ' . base64_encode($params['client_id'] . ":" . $params['client_secret']) 'Authorization' => 'Basic ' . base64_encode($clientId . ":" . $clientSecret)
), ),
$apiContext $apiContext
); );

View File

@@ -466,6 +466,8 @@ class PPOpenIdUserinfo extends ResourceModel
{ {
static $allowedParams = array('schema' => 1); static $allowedParams = array('schema' => 1);
$params = is_array($params) ? $params : array();
if (!array_key_exists('schema', $params)) { if (!array_key_exists('schema', $params)) {
$params['schema'] = 'openid'; $params['schema'] = 'openid';
} }

View File

@@ -79,8 +79,7 @@ class PPHttpConnection
public function execute($data) public function execute($data)
{ {
//Initialize the logger //Initialize the logger
$this->logger->fine("Connecting to " . $this->httpConfig->getUrl()); $this->logger->info($this->httpConfig->getMethod() . ' ' . $this->httpConfig->getUrl());
$this->logger->fine("Payload " . $data);
//Initialize Curl Options //Initialize Curl Options
$ch = curl_init($this->httpConfig->getUrl()); $ch = curl_init($this->httpConfig->getUrl());
@@ -100,18 +99,19 @@ class PPHttpConnection
//Default Option if Method not of given types in switch case //Default Option if Method not of given types in switch case
if ($this->httpConfig->getMethod() != NULL) { if ($this->httpConfig->getMethod() != NULL) {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->httpConfig->getMethod()); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->httpConfig->getMethod());
$this->logger->info("Method : " . $this->httpConfig->getMethod());
} }
//Logging Each Headers for debugging purposes //Logging Each Headers for debugging purposes
foreach ($this->getHttpHeaders() as $header) { foreach ($this->getHttpHeaders() as $header) {
//TODO: Strip out credentials and other secure info when logging. //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 //Execute Curl Request
$result = curl_exec($ch); $result = curl_exec($ch);
//Retry if Certificate Exception //Retry if Certificate Exception
if (curl_errno($ch) == 60) { if (curl_errno($ch) == 60) {
$this->logger->info("Invalid or no certificate authority found - Retrying using bundled CA certs file"); $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()}. " . "Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}. " .
"Retried $retries times." "Retried $retries times."
); );
$this->logger->fine("Response : " . $result . "\n\n");
$ex->setData($result); $ex->setData($result);
throw $ex; throw $ex;
} else if ($httpStatus < 200 || $httpStatus >= 300) { } else if ($httpStatus < 200 || $httpStatus >= 300) {
@@ -159,10 +160,13 @@ class PPHttpConnection
"Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}.", "Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}.",
$httpStatus $httpStatus
); );
$this->logger->fine("Response : " . $result . "\n\n");
$ex->setData($result); $ex->setData($result);
throw $ex; throw $ex;
} }
$this->logger->fine("Response : " . $result . "\n\n");
//Return result object //Return result object
return $result; return $result;
} }

View File

@@ -70,6 +70,11 @@ class PPLoggingManager
*/ */
public function __construct() 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(); $config = PPConfigManager::getInstance()->getConfigHashmap();
$this->isLoggingEnabled = (array_key_exists('log.LogEnabled', $config) && $config['log.LogEnabled'] == '1'); $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) private function log($message, $level = PPLoggingLevel::INFO)
{ {
if ($this->isLoggingEnabled && ($level <= $this->loggingLevel)) { 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);
} }
} }

View File

@@ -72,7 +72,6 @@ class PPRestCall
} }
$connection = new PPHttpConnection($httpConfig, $config); $connection = new PPHttpConnection($httpConfig, $config);
$response = $connection->execute($data); $response = $connection->execute($data);
$this->logger->fine($response . PHP_EOL);
return $response; return $response;
} }

View File

@@ -23,6 +23,7 @@ use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential; use PayPal\Auth\OAuthTokenCredential;
error_reporting(E_ALL); 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 // Replace these values by entering your own ClientId and Secret by visiting https://developer.paypal.com/webapps/developer/applications/myapps
$clientId = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS'; $clientId = 'AYSq3RDGsmBLJE-otTkBtM-jBRd1TCQwFf9RGfwddNXWz0uFU9ztymylOhRS';

View File

@@ -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", "type": "folder",
"data": { "data": {

View File

@@ -22,7 +22,7 @@ required for invoice APIs</p></div></div><div class="code"><div class="wrapper">
-&gt;setShippingInfo(<span class="hljs-keyword">new</span> ShippingInfo());</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="merchant-info">Merchant Info</h3> -&gt;setShippingInfo(<span class="hljs-keyword">new</span> ShippingInfo());</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="merchant-info">Merchant Info</h3>
<p>A resource representing merchant information that can be <p>A resource representing merchant information that can be
used to identify merchant</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$invoice</span>-&gt;getMerchantInfo() used to identify merchant</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$invoice</span>-&gt;getMerchantInfo()
-&gt;setEmail(<span class="hljs-string">"PPX.DevNet-facilitator@gmail.com"</span>) -&gt;setEmail(<span class="hljs-string">"jaypatel512-facilitator@hotmail.com"</span>)
-&gt;setFirstName(<span class="hljs-string">"Dennis"</span>) -&gt;setFirstName(<span class="hljs-string">"Dennis"</span>)
-&gt;setLastName(<span class="hljs-string">"Doctor"</span>) -&gt;setLastName(<span class="hljs-string">"Doctor"</span>)
-&gt;setbusinessName(<span class="hljs-string">"Medical Professionals, LLC"</span>) -&gt;setbusinessName(<span class="hljs-string">"Medical Professionals, LLC"</span>)

View File

@@ -3,7 +3,7 @@
an invoice.</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>; an invoice.</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Invoice</span>; <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Invoice</span>;
<span class="hljs-variable">$invoiceId</span> = <span class="hljs-string">"INV2-9DRB-YTHU-2V9Q-7Q24"</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="retrieve-invoice">Retrieve Invoice</h3> <span class="hljs-variable">$invoiceId</span> = <span class="hljs-string">"INV2-W4LC-6QS9-JZ62-VE4P"</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="retrieve-invoice">Retrieve Invoice</h3>
<p>Retrieve the invoice object by calling the <p>Retrieve the invoice object by calling the
static <code>get</code> method static <code>get</code> method
on the Invoice class by passing a valid on the Invoice class by passing a valid

View File

@@ -10,7 +10,7 @@ an invoice to the payer</p></div></div><div class="code"><div class="wrapper"><s
static <code>get</code> method static <code>get</code> method
on the Invoice class by passing a valid on the Invoice class by passing a valid
Invoice ID Invoice ID
(See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$invoice</span> = Invoice::get(<span class="hljs-string">"INV2-9CAH-K5G7-2JPL-G4B4"</span>, <span class="hljs-variable">$apiContext</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="notification-object">Notification Object</h3> (See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$invoice</span> = Invoice::get(<span class="hljs-string">"INV2-W4LC-6QS9-JZ62-VE4P"</span>, <span class="hljs-variable">$apiContext</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="notification-object">Notification Object</h3>
<p>This would send a notification to both merchant as well <p>This would send a notification to both merchant as well
the payer. The information of merchant the payer. The information of merchant
and payer is retrieved from the invoice details</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$notify</span> = <span class="hljs-keyword">new</span> Notification(); and payer is retrieved from the invoice details</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$notify</span> = <span class="hljs-keyword">new</span> Notification();

View File

@@ -9,7 +9,7 @@ a legitimate invoice to the payer</p></div></div><div class="code"><div class="w
static <code>get</code> method static <code>get</code> method
on the Invoice class by passing a valid on the Invoice class by passing a valid
Invoice ID Invoice ID
(See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$invoice</span> = Invoice::get(<span class="hljs-string">"INV2-9DRB-YTHU-2V9Q-7Q24"</span>, <span class="hljs-variable">$apiContext</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="send-invoice">Send Invoice</h3> (See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$invoice</span> = Invoice::get(<span class="hljs-string">"INV2-W4LC-6QS9-JZ62-VE4P"</span>, <span class="hljs-variable">$apiContext</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="send-invoice">Send Invoice</h3>
<p>Send a legitimate invoice to the payer <p>Send a legitimate invoice to the payer
with a valid ApiContext (See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$sendStatus</span> = <span class="hljs-variable">$invoice</span>-&gt;send(<span class="hljs-variable">$apiContext</span>); with a valid ApiContext (See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$sendStatus</span> = <span class="hljs-variable">$invoice</span>-&gt;send(<span class="hljs-variable">$apiContext</span>);
} <span class="hljs-keyword">catch</span> (PayPal\<span class="hljs-keyword">Exception</span>\PPConnectionException <span class="hljs-variable">$ex</span>) { } <span class="hljs-keyword">catch</span> (PayPal\<span class="hljs-keyword">Exception</span>\PPConnectionException <span class="hljs-variable">$ex</span>) {

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html><html lang="en"><head><title>lipp/GenerateAccessTokenFromRefreshToken</title></head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content="../"><meta name="groc-document-path" content="lipp/GenerateAccessTokenFromRefreshToken"><meta name="groc-project-path" content="lipp/GenerateAccessTokenFromRefreshToken.php"><link rel="stylesheet" type="text/css" media="all" href="../assets/style.css"><script type="text/javascript" src="../assets/behavior.js"></script><body><div id="meta"><div class="file-path">lipp/GenerateAccessTokenFromRefreshToken.php</div></div><div id="document"><div class="segment"><div class="code"><div class="wrapper"><span class="hljs-preprocessor">&lt;?php</span></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="obtain-access-token-from-refresh-token">Obtain Access Token From Refresh Token</h3></div></div></div><div class="segment"><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Auth</span>\<span class="hljs-title">Openid</span>\<span class="hljs-title">PPOpenIdTokeninfo</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>You can retrieve the refresh token by executing ObtainUserConsent.php and store the refresh token</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$refreshToken</span> = <span class="hljs-string">'yzX4AkmMyBKR4on7vB5he-tDu38s24Zy-kTibhSuqA8kTdy0Yinxj7NpAyULx0bxqC5G8dbXOt0aVMlMmtpiVmSzhcjVZhYDM7WUQLC9KpaXGBHyltJPkLLQkXE'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-variable">$tokenInfo</span> = <span class="hljs-keyword">new</span> PPOpenIdTokeninfo();
<span class="hljs-variable">$tokenInfo</span> = <span class="hljs-variable">$tokenInfo</span>-&gt;createFromRefreshToken(<span class="hljs-keyword">array</span>(<span class="hljs-string">'refresh_token'</span> =&gt; <span class="hljs-variable">$refreshToken</span>), <span class="hljs-variable">$apiContext</span>);
} <span class="hljs-keyword">catch</span> (PayPal\<span class="hljs-keyword">Exception</span>\PPConnectionException <span class="hljs-variable">$ex</span>) {
<span class="hljs-keyword">echo</span> <span class="hljs-string">"Exception: "</span> . <span class="hljs-variable">$ex</span>-&gt;getMessage() . PHP_EOL;
var_dump(<span class="hljs-variable">$ex</span>-&gt;getData());
<span class="hljs-keyword">exit</span>(<span class="hljs-number">1</span>);
}
print_result(<span class="hljs-string">"Obtained Access Token From Refresh Token"</span>, <span class="hljs-string">"Access Token"</span>, <span class="hljs-variable">$tokenInfo</span>-&gt;getAccessToken(), <span class="hljs-variable">$tokenInfo</span>);</div></div></div></div></body></html>

View File

@@ -0,0 +1,25 @@
<!DOCTYPE html><html lang="en"><head><title>lipp/GetUserInfo</title></head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content="../"><meta name="groc-document-path" content="lipp/GetUserInfo"><meta name="groc-project-path" content="lipp/GetUserInfo.php"><link rel="stylesheet" type="text/css" media="all" href="../assets/style.css"><script type="text/javascript" src="../assets/behavior.js"></script><body><div id="meta"><div class="file-path">lipp/GetUserInfo.php</div></div><div id="document"><div class="segment"><div class="code"><div class="wrapper"><span class="hljs-preprocessor">&lt;?php</span></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="obtain-access-token-from-refresh-token">Obtain Access Token From Refresh Token</h3></div></div></div><div class="segment"><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Auth</span>\<span class="hljs-title">OpenId</span>\<span class="hljs-title">PPOpenIdTokenInfo</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Auth</span>\<span class="hljs-title">OpenId</span>\<span class="hljs-title">PPOpenIdUserInfo</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>To obtain User Info, you have to follow three steps in general.
First, you need to obtain user&#39;s consent to retrieve the information you want.
This is explained in the example &quot;ObtainUserConsent.php&quot;.</p></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>Once you get the user&#39;s consent, the end result would be long lived refresh token.
This refresh token should be stored in a permanent storage for later use.</p></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>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
&quot;GenerateAccessTokenFromRefreshToken.php&quot;, or as shown below</p></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>You can retrieve the refresh token by executing ObtainUserConsent.php and store the refresh token</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$refreshToken</span> = <span class="hljs-string">'yzX4AkmMyBKR4on7vB5he-tDu38s24Zy-kTibhSuqA8kTdy0Yinxj7NpAyULx0bxqC5G8dbXOt0aVMlMmtpiVmSzhcjVZhYDM7WUQLC9KpaXGBHyltJPkLLQkXE'</span>;
<span class="hljs-keyword">try</span> {
<span class="hljs-variable">$tokenInfo</span> = <span class="hljs-keyword">new</span> PPOpenIdTokeninfo();
<span class="hljs-variable">$tokenInfo</span> = <span class="hljs-variable">$tokenInfo</span>-&gt;createFromRefreshToken(<span class="hljs-keyword">array</span>(<span class="hljs-string">'refresh_token'</span> =&gt; <span class="hljs-variable">$refreshToken</span>), <span class="hljs-variable">$apiContext</span>);
<span class="hljs-variable">$params</span> = <span class="hljs-keyword">array</span>(<span class="hljs-string">'access_token'</span> =&gt; <span class="hljs-variable">$tokenInfo</span>-&gt;getAccessToken());
<span class="hljs-variable">$userInfo</span> = PPOpenIdUserinfo::getUserinfo(<span class="hljs-variable">$params</span>, <span class="hljs-variable">$apiContext</span>);
} <span class="hljs-keyword">catch</span> (PayPal\<span class="hljs-keyword">Exception</span>\PPConnectionException <span class="hljs-variable">$ex</span>) {
<span class="hljs-keyword">echo</span> <span class="hljs-string">"Exception: "</span> . <span class="hljs-variable">$ex</span>-&gt;getMessage() . PHP_EOL;
var_dump(<span class="hljs-variable">$ex</span>-&gt;getData());
<span class="hljs-keyword">exit</span>(<span class="hljs-number">1</span>);
}
print_result(<span class="hljs-string">"User Information"</span>, <span class="hljs-string">"User Info"</span>, <span class="hljs-variable">$userInfo</span>-&gt;getUserId(), <span class="hljs-variable">$userInfo</span>-&gt;toJSON(JSON_PRETTY_PRINT));</div></div></div></div></body></html>

View File

@@ -0,0 +1,18 @@
<!DOCTYPE html><html lang="en"><head><title>lipp/ObtainUserConsent</title></head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content="../"><meta name="groc-document-path" content="lipp/ObtainUserConsent"><meta name="groc-project-path" content="lipp/ObtainUserConsent.php"><link rel="stylesheet" type="text/css" media="all" href="../assets/style.css"><script type="text/javascript" src="../assets/behavior.js"></script><body><div id="meta"><div class="file-path">lipp/ObtainUserConsent.php</div></div><div id="document"><div class="segment"><div class="code"><div class="wrapper"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Auth</span>\<span class="hljs-title">Openid</span>\<span class="hljs-title">PPOpenIdSession</span>;
<span class="hljs-variable">$baseUrl</span> = getBaseUrl() . <span class="hljs-string">'/UserConsentRedirect.php?success=true'</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="get-user-consent-url">Get User Consent URL</h3>
<p>The clientId is stored in the bootstrap file</p></div></div><div class="code"><div class="wrapper"><span class="hljs-comment">//Get Authorization URL returns the redirect URL that could be used to get user's consent</span>
<span class="hljs-variable">$redirectUrl</span> = PPOpenIdSession::getAuthorizationUrl(
<span class="hljs-variable">$baseUrl</span>,
<span class="hljs-keyword">array</span>(<span class="hljs-string">'profile'</span>, <span class="hljs-string">'email'</span>, <span class="hljs-string">'phone'</span>),
<span class="hljs-keyword">null</span>,
<span class="hljs-keyword">null</span>,
<span class="hljs-keyword">null</span>,
<span class="hljs-variable">$apiContext</span>
);
print_result(<span class="hljs-string">"Generated the User Consent URL"</span>, <span class="hljs-string">"URL"</span>, <span class="hljs-keyword">null</span>, <span class="hljs-string">'&lt;a href="'</span>. <span class="hljs-variable">$redirectUrl</span> . <span class="hljs-string">'" &gt;Click Here to Obtain User Consent&lt;/a&gt;'</span>);</div></div></div></div></body></html>

View File

@@ -0,0 +1,23 @@
<!DOCTYPE html><html lang="en"><head><title>lipp/UserConsentRedirect</title></head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0"><meta name="groc-relative-root" content="../"><meta name="groc-document-path" content="lipp/UserConsentRedirect"><meta name="groc-project-path" content="lipp/UserConsentRedirect.php"><link rel="stylesheet" type="text/css" media="all" href="../assets/style.css"><script type="text/javascript" src="../assets/behavior.js"></script><body><div id="meta"><div class="file-path">lipp/UserConsentRedirect.php</div></div><div id="document"><div class="segment"><div class="code"><div class="wrapper"><span class="hljs-preprocessor">&lt;?php</span>
<span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Auth</span>\<span class="hljs-title">Openid</span>\<span class="hljs-title">PPOpenIdTokeninfo</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Exception</span>\<span class="hljs-title">PPConnectionException</span>;
session_start();</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="user-consent-response">User Consent Response</h3>
<p>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.</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>(<span class="hljs-variable">$_GET</span>[<span class="hljs-string">'success'</span>]) &amp;&amp; <span class="hljs-variable">$_GET</span>[<span class="hljs-string">'success'</span>] == <span class="hljs-string">'true'</span>) {
<span class="hljs-variable">$code</span> = <span class="hljs-variable">$_GET</span>[<span class="hljs-string">'code'</span>];
<span class="hljs-keyword">try</span> {</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>Obtain Authorization Code from Code, Client ID and Client Secret</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$accessToken</span> = PPOpenIdTokeninfo::createFromAuthorizationCode(<span class="hljs-keyword">array</span>(<span class="hljs-string">'code'</span> =&gt; <span class="hljs-variable">$code</span>), <span class="hljs-keyword">null</span>, <span class="hljs-keyword">null</span>, <span class="hljs-variable">$apiContext</span>);
} <span class="hljs-keyword">catch</span> (PPConnectionException <span class="hljs-variable">$ex</span>) {
<span class="hljs-keyword">echo</span> <span class="hljs-string">"Exception: "</span> . <span class="hljs-variable">$ex</span>-&gt;getMessage() . PHP_EOL;
var_dump(<span class="hljs-variable">$ex</span>-&gt;getData());
<span class="hljs-keyword">exit</span>(<span class="hljs-number">1</span>);
}
print_result(<span class="hljs-string">"Obtained Access Token"</span>, <span class="hljs-string">"Access Token"</span>, <span class="hljs-variable">$accessToken</span>-&gt;getAccessToken(), <span class="hljs-variable">$accessToken</span>);
}</div></div></div></div></body></html>

View File

@@ -3,11 +3,8 @@
PayPal Account based Payment. PayPal Account based Payment.
API used: /v1/payments/payment</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>; API used: /v1/payments/payment</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Amount</span>; <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Amount</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Details</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Item</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">ItemList</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Payer</span>; <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Payer</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Payment</span>; <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">FuturePayment</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">RedirectUrls</span>; <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">RedirectUrls</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Transaction</span>; <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Transaction</span>;
session_start();</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="payer">Payer</h3> session_start();</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="payer">Payer</h3>
@@ -31,22 +28,22 @@ payment approval/ cancellation.</p></div></div><div class="code"><div class="wra
<span class="hljs-variable">$redirectUrls</span>-&gt;setReturnUrl(<span class="hljs-string">"$baseUrl/ExecutePayment.php?success=true"</span>) <span class="hljs-variable">$redirectUrls</span>-&gt;setReturnUrl(<span class="hljs-string">"$baseUrl/ExecutePayment.php?success=true"</span>)
-&gt;setCancelUrl(<span class="hljs-string">"$baseUrl/ExecutePayment.php?success=false"</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="payment">Payment</h3> -&gt;setCancelUrl(<span class="hljs-string">"$baseUrl/ExecutePayment.php?success=false"</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="payment">Payment</h3>
<p>A Payment Resource; create one using <p>A Payment Resource; create one using
the above types and intent set to &#39;sale&#39;</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$payment</span> = <span class="hljs-keyword">new</span> Payment(); the above types and intent set to &#39;sale&#39;</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$payment</span> = <span class="hljs-keyword">new</span> FuturePayment();
<span class="hljs-variable">$payment</span>-&gt;setIntent(<span class="hljs-string">"authorize"</span>) <span class="hljs-variable">$payment</span>-&gt;setIntent(<span class="hljs-string">"authorize"</span>)
-&gt;setPayer(<span class="hljs-variable">$payer</span>) -&gt;setPayer(<span class="hljs-variable">$payer</span>)
-&gt;setRedirectUrls(<span class="hljs-variable">$redirectUrls</span>) -&gt;setRedirectUrls(<span class="hljs-variable">$redirectUrls</span>)
-&gt;setTransactions(<span class="hljs-keyword">array</span>(<span class="hljs-variable">$transaction</span>));</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="get-refresh-token">Get Refresh Token</h3> -&gt;setTransactions(<span class="hljs-keyword">array</span>(<span class="hljs-variable">$transaction</span>));</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="get-refresh-token">Get Refresh Token</h3>
<p>You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.</p></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>authorization code from mobile sdk</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$authorizationCode</span> = <span class="hljs-string">'EF4Ds2Wv1JbHiU_UuhR5v-ftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY'</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>correlation id from mobile sdk</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$correlationId</span> = <span class="hljs-string">'123123456'</span>; <p>You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.</p></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>authorization code from mobile sdk</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$authorizationCode</span> = <span class="hljs-string">'EJfRuAqXEE95pdVMmOym_mftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY'</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>correlation id from mobile sdk</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$correlationId</span> = <span class="hljs-string">'123123456'</span>;
<span class="hljs-keyword">try</span> {</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>Exchange authorization_code for long living refresh token. You should store <span class="hljs-keyword">try</span> {</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>Exchange authorization_code for long living refresh token. You should store
it in a database for later use</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$refreshToken</span> = <span class="hljs-variable">$apiContext</span>-&gt;getCredential()-&gt;getRefreshToken(<span class="hljs-variable">$apiContext</span>-&gt;getConfig(), <span class="hljs-variable">$authorizationCode</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>Update the access token in apiContext</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$apiContext</span>-&gt;getCredential()-&gt;updateAccessToken(<span class="hljs-variable">$apiContext</span>-&gt;getConfig(), <span class="hljs-variable">$refreshToken</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="create-future-payment">Create Future Payment</h3> it in a database for later use</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$refreshToken</span> = FuturePayment::getRefreshToken(<span class="hljs-variable">$authorizationCode</span>, <span class="hljs-variable">$apiContext</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>Update the access token in apiContext</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$payment</span>-&gt;updateAccessToken(<span class="hljs-variable">$refreshToken</span>, <span class="hljs-variable">$apiContext</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="create-future-payment">Create Future Payment</h3>
<p>Create a payment by calling the &#39;create&#39; method <p>Create a payment by calling the &#39;create&#39; method
passing it a valid apiContext. passing it a valid apiContext.
(See bootstrap.php for more on <code>ApiContext</code>) (See bootstrap.php for more on <code>ApiContext</code>)
The return object contains the state and the The return object contains the state and the
url to which the buyer must be redirected to url to which the buyer must be redirected to
for payment approval for payment approval
Please note that currently future payments works only with Paypal as a funding instrument.</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$payment</span>-&gt;create(<span class="hljs-variable">$apiContext</span>, <span class="hljs-variable">$correlationId</span>); Please note that currently future payments works only with PayPal as a funding instrument.</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$payment</span>-&gt;create(<span class="hljs-variable">$apiContext</span>, <span class="hljs-variable">$correlationId</span>);
} <span class="hljs-keyword">catch</span> (PayPal\<span class="hljs-keyword">Exception</span>\PPConnectionException <span class="hljs-variable">$ex</span>) { } <span class="hljs-keyword">catch</span> (PayPal\<span class="hljs-keyword">Exception</span>\PPConnectionException <span class="hljs-variable">$ex</span>) {
<span class="hljs-keyword">echo</span> <span class="hljs-string">"Exception: "</span> . <span class="hljs-variable">$ex</span>-&gt;getMessage() . PHP_EOL; <span class="hljs-keyword">echo</span> <span class="hljs-string">"Exception: "</span> . <span class="hljs-variable">$ex</span>-&gt;getMessage() . PHP_EOL;

View File

@@ -13,7 +13,7 @@ API used: /v1/payments/payment</p></div></div><div class="code"><div class="wrap
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Transaction</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="credit-card-token">Credit card token</h3> <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Transaction</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="credit-card-token">Credit card token</h3>
<p>Saved credit card id from a previous call to <p>Saved credit card id from a previous call to
CreateCreditCard.php</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$creditCardToken</span> = <span class="hljs-keyword">new</span> CreditCardToken(); CreateCreditCard.php</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$creditCardToken</span> = <span class="hljs-keyword">new</span> CreditCardToken();
<span class="hljs-variable">$creditCardToken</span>-&gt;setCreditCardId(<span class="hljs-string">'CARD-29H07236G1554552FKINPBHQ'</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="fundinginstrument">FundingInstrument</h3> <span class="hljs-variable">$creditCardToken</span>-&gt;setCreditCardId(<span class="hljs-string">'CARD-17M96700G1952584EKRCTV5Y'</span>);</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="fundinginstrument">FundingInstrument</h3>
<p>A resource representing a Payer&#39;s funding instrument. <p>A resource representing a Payer&#39;s funding instrument.
For stored credit card payments, set the CreditCardToken For stored credit card payments, set the CreditCardToken
field on this object.</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$fi</span> = <span class="hljs-keyword">new</span> FundingInstrument(); field on this object.</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$fi</span> = <span class="hljs-keyword">new</span> FundingInstrument();

View File

@@ -22,10 +22,12 @@ when the user is redirected from paypal back to your site</p></div></div><div cl
<span class="hljs-comment">//Execute the payment</span></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>(See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$result</span> = <span class="hljs-variable">$payment</span>-&gt;execute(<span class="hljs-variable">$execution</span>, <span class="hljs-variable">$apiContext</span>); <span class="hljs-comment">//Execute the payment</span></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>(See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"> <span class="hljs-variable">$result</span> = <span class="hljs-variable">$payment</span>-&gt;execute(<span class="hljs-variable">$execution</span>, <span class="hljs-variable">$apiContext</span>);
<span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;html&gt;&lt;body&gt;&lt;pre&gt;"</span>; <span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;html&gt;&lt;body&gt;&lt;pre&gt;"</span>;
<span class="hljs-keyword">echo</span> <span class="hljs-variable">$result</span>-&gt;toJSON(JSON_PRETTY_PRINT); <span class="hljs-keyword">echo</span> <span class="hljs-variable">$result</span>-&gt;toJSON(JSON_PRETTY_PRINT);
<span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;/pre&gt;&lt;a href='../index.html'&gt;Back&lt;/a&gt;&lt;/body&gt;&lt;/html&gt;"</span>; <span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;/pre&gt;&lt;a href='../index.html'&gt;Back&lt;/a&gt;&lt;/body&gt;&lt;/html&gt;"</span>;
} <span class="hljs-keyword">else</span> { } <span class="hljs-keyword">else</span> {
<span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;html&gt;&lt;body&gt;&lt;h1&gt;"</span>;
<span class="hljs-keyword">echo</span> <span class="hljs-string">"User cancelled payment."</span>; <span class="hljs-keyword">echo</span> <span class="hljs-string">"User cancelled payment."</span>;
<span class="hljs-keyword">echo</span> <span class="hljs-string">"&lt;/h1&gt;&lt;a href='../index.html'&gt;Back&lt;/a&gt;&lt;/body&gt;&lt;/html&gt;"</span>;
}</div></div></div></div></body></html> }</div></div></div></div></body></html>

View File

@@ -8,7 +8,7 @@ payments list.
API used: GET /v1/payments/payments</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>; API used: GET /v1/payments/payments</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Payment</span>; <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">Payment</span>;
<span class="hljs-variable">$paymentId</span> = <span class="hljs-string">"PAY-0XL713371A312273YKE2GCNI"</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="retrieve-payment">Retrieve payment</h3> <span class="hljs-variable">$paymentId</span> = <span class="hljs-string">"PAY-2AH507590P6615624KRCTUSY"</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><h3 id="retrieve-payment">Retrieve payment</h3>
<p>Retrieve the payment object by calling the <p>Retrieve the payment object by calling the
static <code>get</code> method static <code>get</code> method
on the Payment class by passing a valid on the Payment class by passing a valid

View File

@@ -5,7 +5,7 @@ API called: &#39;/v1/vault/credit-card&#39;
The following code takes you through The following code takes you through
the process of retrieving a saved CreditCard</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>; the process of retrieving a saved CreditCard</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">require</span> <span class="hljs-keyword">__DIR__</span> . <span class="hljs-string">'/../bootstrap.php'</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">CreditCard</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>The cardId can be obtained from a previous save credit <span class="hljs-keyword">use</span> <span class="hljs-title">PayPal</span>\<span class="hljs-title">Api</span>\<span class="hljs-title">CreditCard</span>;</div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>The cardId can be obtained from a previous save credit
card operation. Use $card-&gt;getId()</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$cardId</span> = <span class="hljs-string">"CARD-5AR29593TC404090HKIKN77Q"</span>; card operation. Use $card-&gt;getId()</p></div></div><div class="code"><div class="wrapper"><span class="hljs-variable">$cardId</span> = <span class="hljs-string">"CARD-44D10970C24287906KRCTWNI"</span>;
<span class="hljs-comment">/// ### Retrieve card</span></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>(See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">try</span> { <span class="hljs-comment">/// ### Retrieve card</span></div></div></div><div class="segment"><div class="comments "><div class="wrapper"><p>(See bootstrap.php for more on <code>ApiContext</code>)</p></div></div><div class="code"><div class="wrapper"><span class="hljs-keyword">try</span> {
<span class="hljs-variable">$card</span> = CreditCard::get(<span class="hljs-variable">$cardId</span>, <span class="hljs-variable">$apiContext</span>); <span class="hljs-variable">$card</span> = CreditCard::get(<span class="hljs-variable">$cardId</span>, <span class="hljs-variable">$apiContext</span>);

View File

@@ -360,6 +360,50 @@
</li> </li>
</ul> </ul>
</div> </div>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Identity (LIPP)</h3>
</div>
<!-- List group -->
<ul class="list-group">
<li class="list-group-item">
<div class="row">
<div class="col-md-9 "><h5>Obtain User's Consent</h5></div>
<div class="col-md-3">
<a href="lipp/ObtainUserConsent.php" class="btn btn-primary pull-left" >Execute <i class="fa fa-play-circle-o"></i></a>
<a href="doc/lipp/ObtainUserConsent.html" class="btn btn-default pull-right" >Source <i class="fa fa-file-code-o"></i></a>
</div>
</div>
</li>
<li class="list-group-item">
<div class="row">
<div class="col-md-9 "><h5>User Consent Redirect</h5></div>
<div class="col-md-3">
<a href="doc/lipp/UserConsentRedirect.html" class="btn btn-default pull-right" >Source <i class="fa fa-file-code-o"></i></a>
</div>
</div>
</li>
<li class="list-group-item">
<div class="row">
<div class="col-md-9 "><h5>Get User Info</h5></div>
<div class="col-md-3">
<a href="lipp/GetUserInfo.php" class="btn btn-primary pull-left" >Execute <i class="fa fa-play-circle-o"></i></a>
<a href="doc/lipp/GetUserInfo.html" class="btn btn-default pull-right" >Source <i class="fa fa-file-code-o"></i></a>
</div>
</div>
</li>
<li class="list-group-item">
<div class="row">
<div class="col-md-9 "><h5>Obtain Access Token From Refresh Token</h5></div>
<div class="col-md-3">
<a href="lipp/GenerateAccessTokenFromRefreshToken.php" class="btn btn-primary pull-left" >Execute <i class="fa fa-play-circle-o"></i></a>
<a href="doc/lipp/GenerateAccessTokenFromRefreshToken.html" class="btn btn-default pull-right" >Source <i class="fa fa-file-code-o"></i></a>
</div>
</div>
</li>
</ul>
</div>
</div> </div>
</div> <!-- /container --> </div> <!-- /container -->

View File

@@ -32,7 +32,7 @@ $invoice
// A resource representing merchant information that can be // A resource representing merchant information that can be
// used to identify merchant // used to identify merchant
$invoice->getMerchantInfo() $invoice->getMerchantInfo()
->setEmail("PPX.DevNet-facilitator@gmail.com") ->setEmail("jaypatel512-facilitator@hotmail.com")
->setFirstName("Dennis") ->setFirstName("Dennis")
->setLastName("Doctor") ->setLastName("Doctor")
->setbusinessName("Medical Professionals, LLC") ->setbusinessName("Medical Professionals, LLC")

View File

@@ -7,7 +7,7 @@
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Invoice; use PayPal\Api\Invoice;
$invoiceId = "INV2-9DRB-YTHU-2V9Q-7Q24"; $invoiceId = "INV2-W4LC-6QS9-JZ62-VE4P";
// ### Retrieve Invoice // ### Retrieve Invoice
// Retrieve the invoice object by calling the // Retrieve the invoice object by calling the

View File

@@ -16,7 +16,7 @@ try {
// on the Invoice class by passing a valid // on the Invoice class by passing a valid
// Invoice ID // Invoice ID
// (See bootstrap.php for more on `ApiContext`) // (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 // ### Notification Object
// This would send a notification to both merchant as well // This would send a notification to both merchant as well

View File

@@ -15,7 +15,7 @@ try {
// on the Invoice class by passing a valid // on the Invoice class by passing a valid
// Invoice ID // Invoice ID
// (See bootstrap.php for more on `ApiContext`) // (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 Invoice
// Send a legitimate invoice to the payer // Send a legitimate invoice to the payer

View File

@@ -1,19 +1,18 @@
<?php <?php
// ### Obtain Access Token From Refresh Token
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Auth\Openid\PPOpenIdTokeninfo;
// You can retrieve the refresh token by executing ObtainUserConsent.php and store the refresh token // You can retrieve the refresh token by executing ObtainUserConsent.php and store the refresh token
$refreshToken = 'yzX4AkmMyBKR4on7vB5he-tDu38s24Zy-kTibhSuqA8kTdy0Yinxj7NpAyULx0bxqC5G8dbXOt0aVMlMmtpiVmSzhcjVZhYDM7WUQLC9KpaXGBHyltJPkLLQkXE'; $refreshToken = 'yzX4AkmMyBKR4on7vB5he-tDu38s24Zy-kTibhSuqA8kTdy0Yinxj7NpAyULx0bxqC5G8dbXOt0aVMlMmtpiVmSzhcjVZhYDM7WUQLC9KpaXGBHyltJPkLLQkXE';
$params = array(
'refresh_token' => $refreshToken,
'redirect_uri' => getBaseUrl() . '/UserConsentRedirect.php?success=true',
'client_id' => $clientId,
'client_secret' => $clientSecret
);
try { 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) { } catch (PayPal\Exception\PPConnectionException $ex) {
echo "Exception: " . $ex->getMessage() . PHP_EOL; echo "Exception: " . $ex->getMessage() . PHP_EOL;
var_dump($ex->getData()); var_dump($ex->getData());

View File

@@ -0,0 +1,37 @@
<?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));

View File

@@ -0,0 +1,22 @@
<?php
require __DIR__ . '/../bootstrap.php';
use PayPal\Auth\Openid\PPOpenIdSession;
$baseUrl = getBaseUrl() . '/UserConsentRedirect.php?success=true';
// ### Get User Consent URL
// 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>');

View File

@@ -0,0 +1,28 @@
<?php
require __DIR__ . '/../bootstrap.php';
use PayPal\Auth\Openid\PPOpenIdTokeninfo;
use PayPal\Exception\PPConnectionException;
session_start();
// ### User Consent Response
// 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);
}

View File

@@ -1,20 +0,0 @@
<?php
require __DIR__ . '/../bootstrap.php';
$baseUrl = getBaseUrl() . '/UserConsentRedirect.php?success=true';
//Get User Consent
// The clientId is stored in the bootstrap file
$redirectUrl = \PayPal\Auth\Openid\PPOpenIdSession::getAuthorizationUrl(
$baseUrl,
array('profile', 'email', 'phone'),
$clientId,
null,
null,
$apiContext
);
header("Location: $redirectUrl");
exit;

View File

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

View File

@@ -7,11 +7,8 @@
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Amount; use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer; use PayPal\Api\Payer;
use PayPal\Api\Payment; use PayPal\Api\FuturePayment;
use PayPal\Api\RedirectUrls; use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction; use PayPal\Api\Transaction;
session_start(); session_start();
@@ -50,7 +47,7 @@ $redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
// ### Payment // ### Payment
// A Payment Resource; create one using // A Payment Resource; create one using
// the above types and intent set to 'sale' // the above types and intent set to 'sale'
$payment = new Payment(); $payment = new FuturePayment();
$payment->setIntent("authorize") $payment->setIntent("authorize")
->setPayer($payer) ->setPayer($payer)
->setRedirectUrls($redirectUrls) ->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. // You need to get a permanent refresh token from the authorization code, retrieved from the mobile sdk.
// authorization code from mobile sdk // authorization code from mobile sdk
$authorizationCode = 'EF4Ds2Wv1JbHiU_UuhR5v-ftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY'; $authorizationCode = 'EJfRuAqXEE95pdVMmOym_mftTbeJD03RBX-Zjg9pLCAhdLqLeRR6YSKTNsrbQGX7lFoZ3SxwFyxADEZbBOxpn023W9SA0JzSQAy-9eLdON5eDPAyMyKlHyNVS2DqBR2iWVfQGfudbd9MDoRxMEjIZbY';
// correlation id from mobile sdk // correlation id from mobile sdk
$correlationId = '123123456'; $correlationId = '123123456';
@@ -68,10 +65,10 @@ $correlationId = '123123456';
try { try {
// Exchange authorization_code for long living refresh token. You should store // Exchange authorization_code for long living refresh token. You should store
// it in a database for later use // 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 // Update the access token in apiContext
$apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refreshToken); $payment->updateAccessToken($refreshToken, $apiContext);
// ### Create Future Payment // ### Create Future Payment
// Create a payment by calling the 'create' method // Create a payment by calling the 'create' method
@@ -80,7 +77,7 @@ try {
// The return object contains the state and the // The return object contains the state and the
// url to which the buyer must be redirected to // url to which the buyer must be redirected to
// for payment approval // 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); $payment->create($apiContext, $correlationId);
} catch (PayPal\Exception\PPConnectionException $ex) { } catch (PayPal\Exception\PPConnectionException $ex) {

View File

@@ -1,129 +1,129 @@
<?php <?php
// # CreatePaymentSample // # CreatePaymentSample
// //
// This sample code demonstrate how you can process // This sample code demonstrate how you can process
// a direct credit card payment. Please note that direct // a direct credit card payment. Please note that direct
// credit card payment and related features using the // credit card payment and related features using the
// REST API is restricted in some countries. // REST API is restricted in some countries.
// API used: /v1/payments/payment // API used: /v1/payments/payment
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Amount; use PayPal\Api\Amount;
use PayPal\Api\Details; use PayPal\Api\Details;
use PayPal\Api\Item; use PayPal\Api\Item;
use PayPal\Api\ItemList; use PayPal\Api\ItemList;
use PayPal\Api\CreditCard; use PayPal\Api\CreditCard;
use PayPal\Api\Payer; use PayPal\Api\Payer;
use PayPal\Api\Payment; use PayPal\Api\Payment;
use PayPal\Api\FundingInstrument; use PayPal\Api\FundingInstrument;
use PayPal\Api\Transaction; use PayPal\Api\Transaction;
// ### CreditCard // ### CreditCard
// A resource representing a credit card that can be // A resource representing a credit card that can be
// used to fund a payment. // used to fund a payment.
$card = new CreditCard(); $card = new CreditCard();
$card->setType("visa") $card->setType("visa")
->setNumber("4417119669820331") ->setNumber("4417119669820331")
->setExpireMonth("11") ->setExpireMonth("11")
->setExpireYear("2019") ->setExpireYear("2019")
->setCvv2("012") ->setCvv2("012")
->setFirstName("Joe") ->setFirstName("Joe")
->setLastName("Shopper"); ->setLastName("Shopper");
// ### FundingInstrument // ### FundingInstrument
// A resource representing a Payer's funding instrument. // A resource representing a Payer's funding instrument.
// For direct credit card payments, set the CreditCard // For direct credit card payments, set the CreditCard
// field on this object. // field on this object.
$fi = new FundingInstrument(); $fi = new FundingInstrument();
$fi->setCreditCard($card); $fi->setCreditCard($card);
// ### Payer // ### Payer
// A resource representing a Payer that funds a payment // A resource representing a Payer that funds a payment
// For direct credit card payments, set payment method // For direct credit card payments, set payment method
// to 'credit_card' and add an array of funding instruments. // to 'credit_card' and add an array of funding instruments.
$payer = new Payer(); $payer = new Payer();
$payer->setPaymentMethod("credit_card") $payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi)); ->setFundingInstruments(array($fi));
// ### Itemized information // ### Itemized information
// (Optional) Lets you specify item wise // (Optional) Lets you specify item wise
// information // information
$item1 = new Item(); $item1 = new Item();
$item1->setName('Ground Coffee 40 oz') $item1->setName('Ground Coffee 40 oz')
->setDescription('Ground Coffee 40 oz') ->setDescription('Ground Coffee 40 oz')
->setCurrency('USD') ->setCurrency('USD')
->setQuantity(1) ->setQuantity(1)
->setTax('0.30') ->setTax('0.30')
->setPrice('7.50'); ->setPrice('7.50');
$item2 = new Item(); $item2 = new Item();
$item2->setName('Granola bars') $item2->setName('Granola bars')
->setDescription('Granola Bars with Peanuts') ->setDescription('Granola Bars with Peanuts')
->setCurrency('USD') ->setCurrency('USD')
->setQuantity(5) ->setQuantity(5)
->setTax('0.20') ->setTax('0.20')
->setPrice('2.00'); ->setPrice('2.00');
$itemList = new ItemList(); $itemList = new ItemList();
$itemList->setItems(array($item1, $item2)); $itemList->setItems(array($item1, $item2));
// ### Additional payment details // ### Additional payment details
// Use this optional field to set additional // Use this optional field to set additional
// payment information such as tax, shipping // payment information such as tax, shipping
// charges etc. // charges etc.
$details = new Details(); $details = new Details();
$details->setShipping('1.20') $details->setShipping('1.20')
->setTax('1.30') ->setTax('1.30')
->setSubtotal('17.50'); ->setSubtotal('17.50');
// ### Amount // ### Amount
// Lets you specify a payment amount. // Lets you specify a payment amount.
// You can also specify additional details // You can also specify additional details
// such as shipping, tax. // such as shipping, tax.
$amount = new Amount(); $amount = new Amount();
$amount->setCurrency("USD") $amount->setCurrency("USD")
->setTotal("20.00") ->setTotal("20.00")
->setDetails($details); ->setDetails($details);
// ### Transaction // ### Transaction
// A transaction defines the contract of a // A transaction defines the contract of a
// payment - what is the payment for and who // payment - what is the payment for and who
// is fulfilling it. // is fulfilling it.
$transaction = new Transaction(); $transaction = new Transaction();
$transaction->setAmount($amount) $transaction->setAmount($amount)
->setItemList($itemList) ->setItemList($itemList)
->setDescription("Payment description"); ->setDescription("Payment description");
// ### Payment // ### Payment
// A Payment Resource; create one using // A Payment Resource; create one using
// the above types and intent set to sale 'sale' // the above types and intent set to sale 'sale'
$payment = new Payment(); $payment = new Payment();
$payment->setIntent("sale") $payment->setIntent("sale")
->setPayer($payer) ->setPayer($payer)
->setTransactions(array($transaction)); ->setTransactions(array($transaction));
// ### Create Payment // ### Create Payment
// Create a payment by calling the payment->create() method // Create a payment by calling the payment->create() method
// with a valid ApiContext (See bootstrap.php for more on `ApiContext`) // with a valid ApiContext (See bootstrap.php for more on `ApiContext`)
// The return object contains the state. // The return object contains the state.
try { try {
$payment->create($apiContext); $payment->create($apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) { } catch (PayPal\Exception\PPConnectionException $ex) {
echo "Exception: " . $ex->getMessage() . PHP_EOL; echo "Exception: " . $ex->getMessage() . PHP_EOL;
var_dump($ex->getData()); var_dump($ex->getData());
exit(1); exit(1);
} }
?> ?>
<html> <html>
<head> <head>
<title>Direct Credit card payments</title> <title>Direct Credit card payments</title>
</head> </head>
<body> <body>
<div> <div>
Created payment: Created payment:
<?php echo $payment->getId();?> <?php echo $payment->getId();?>
</div> </div>
<pre><?php echo $payment->toJSON(JSON_PRETTY_PRINT);?></pre> <pre><?php echo $payment->toJSON(JSON_PRETTY_PRINT);?></pre>
<a href='../index.html'>Back</a> <a href='../index.html'>Back</a>
</body> </body>
</html> </html>

View File

@@ -1,125 +1,125 @@
<?php <?php
// # Create Payment using PayPal as payment method // # Create Payment using PayPal as payment method
// This sample code demonstrates how you can process a // This sample code demonstrates how you can process a
// PayPal Account based Payment. // PayPal Account based Payment.
// API used: /v1/payments/payment // API used: /v1/payments/payment
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Amount; use PayPal\Api\Amount;
use PayPal\Api\Details; use PayPal\Api\Details;
use PayPal\Api\Item; use PayPal\Api\Item;
use PayPal\Api\ItemList; use PayPal\Api\ItemList;
use PayPal\Api\Payer; use PayPal\Api\Payer;
use PayPal\Api\Payment; use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls; use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction; use PayPal\Api\Transaction;
session_start(); session_start();
// ### Payer // ### Payer
// A resource representing a Payer that funds a payment // A resource representing a Payer that funds a payment
// For paypal account payments, set payment method // For paypal account payments, set payment method
// to 'paypal'. // to 'paypal'.
$payer = new Payer(); $payer = new Payer();
$payer->setPaymentMethod("paypal"); $payer->setPaymentMethod("paypal");
// ### Itemized information // ### Itemized information
// (Optional) Lets you specify item wise // (Optional) Lets you specify item wise
// information // information
$item1 = new Item(); $item1 = new Item();
$item1->setName('Ground Coffee 40 oz') $item1->setName('Ground Coffee 40 oz')
->setCurrency('USD') ->setCurrency('USD')
->setQuantity(1) ->setQuantity(1)
->setPrice('7.50'); ->setPrice('7.50');
$item2 = new Item(); $item2 = new Item();
$item2->setName('Granola bars') $item2->setName('Granola bars')
->setCurrency('USD') ->setCurrency('USD')
->setQuantity(5) ->setQuantity(5)
->setPrice('2.00'); ->setPrice('2.00');
$itemList = new ItemList(); $itemList = new ItemList();
$itemList->setItems(array($item1, $item2)); $itemList->setItems(array($item1, $item2));
// ### Additional payment details // ### Additional payment details
// Use this optional field to set additional // Use this optional field to set additional
// payment information such as tax, shipping // payment information such as tax, shipping
// charges etc. // charges etc.
$details = new Details(); $details = new Details();
$details->setShipping('1.20') $details->setShipping('1.20')
->setTax('1.30') ->setTax('1.30')
->setSubtotal('17.50'); ->setSubtotal('17.50');
// ### Amount // ### Amount
// Lets you specify a payment amount. // Lets you specify a payment amount.
// You can also specify additional details // You can also specify additional details
// such as shipping, tax. // such as shipping, tax.
$amount = new Amount(); $amount = new Amount();
$amount->setCurrency("USD") $amount->setCurrency("USD")
->setTotal("20.00") ->setTotal("20.00")
->setDetails($details); ->setDetails($details);
// ### Transaction // ### Transaction
// A transaction defines the contract of a // A transaction defines the contract of a
// payment - what is the payment for and who // payment - what is the payment for and who
// is fulfilling it. // is fulfilling it.
$transaction = new Transaction(); $transaction = new Transaction();
$transaction->setAmount($amount) $transaction->setAmount($amount)
->setItemList($itemList) ->setItemList($itemList)
->setDescription("Payment description"); ->setDescription("Payment description");
// ### Redirect urls // ### Redirect urls
// Set the urls that the buyer must be redirected to after // Set the urls that the buyer must be redirected to after
// payment approval/ cancellation. // payment approval/ cancellation.
$baseUrl = getBaseUrl(); $baseUrl = getBaseUrl();
$redirectUrls = new RedirectUrls(); $redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true") $redirectUrls->setReturnUrl("$baseUrl/ExecutePayment.php?success=true")
->setCancelUrl("$baseUrl/ExecutePayment.php?success=false"); ->setCancelUrl("$baseUrl/ExecutePayment.php?success=false");
// ### Payment // ### Payment
// A Payment Resource; create one using // A Payment Resource; create one using
// the above types and intent set to 'sale' // the above types and intent set to 'sale'
$payment = new Payment(); $payment = new Payment();
$payment->setIntent("sale") $payment->setIntent("sale")
->setPayer($payer) ->setPayer($payer)
->setRedirectUrls($redirectUrls) ->setRedirectUrls($redirectUrls)
->setTransactions(array($transaction)); ->setTransactions(array($transaction));
// ### Create Payment // ### Create Payment
// Create a payment by calling the 'create' method // Create a payment by calling the 'create' method
// passing it a valid apiContext. // passing it a valid apiContext.
// (See bootstrap.php for more on `ApiContext`) // (See bootstrap.php for more on `ApiContext`)
// The return object contains the state and the // The return object contains the state and the
// url to which the buyer must be redirected to // url to which the buyer must be redirected to
// for payment approval // for payment approval
try { try {
$payment->create($apiContext); $payment->create($apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) { } catch (PayPal\Exception\PPConnectionException $ex) {
echo "Exception: " . $ex->getMessage() . PHP_EOL; echo "Exception: " . $ex->getMessage() . PHP_EOL;
var_dump($ex->getData()); var_dump($ex->getData());
exit(1); exit(1);
} }
// ### Get redirect url // ### Get redirect url
// The API response provides the url that you must redirect // The API response provides the url that you must redirect
// the buyer to. Retrieve the url from the $payment->getLinks() // the buyer to. Retrieve the url from the $payment->getLinks()
// method // method
foreach($payment->getLinks() as $link) { foreach($payment->getLinks() as $link) {
if($link->getRel() == 'approval_url') { if($link->getRel() == 'approval_url') {
$redirectUrl = $link->getHref(); $redirectUrl = $link->getHref();
break; break;
} }
} }
// ### Redirect buyer to PayPal website // ### Redirect buyer to PayPal website
// Save the payment id so that you can 'complete' the payment // Save the payment id so that you can 'complete' the payment
// once the buyer approves the payment and is redirected // once the buyer approves the payment and is redirected
// back to your website. // back to your website.
// //
// It is not a great idea to store the payment id // It is not a great idea to store the payment id
// in the session. In a real world app, you may want to // in the session. In a real world app, you may want to
// store the payment id in a database. // store the payment id in a database.
$_SESSION['paymentId'] = $payment->getId(); $_SESSION['paymentId'] = $payment->getId();
if(isset($redirectUrl)) { if(isset($redirectUrl)) {
header("Location: $redirectUrl"); header("Location: $redirectUrl");
exit; exit;
} }

View File

@@ -1,117 +1,117 @@
<?php <?php
// # Create payment using a saved credit card // # Create payment using a saved credit card
// This sample code demonstrates how you can process a // This sample code demonstrates how you can process a
// Payment using a previously stored credit card token. // Payment using a previously stored credit card token.
// API used: /v1/payments/payment // API used: /v1/payments/payment
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Amount; use PayPal\Api\Amount;
use PayPal\Api\Details; use PayPal\Api\Details;
use PayPal\Api\Item; use PayPal\Api\Item;
use PayPal\Api\ItemList; use PayPal\Api\ItemList;
use PayPal\Api\CreditCardToken; use PayPal\Api\CreditCardToken;
use PayPal\Api\Payer; use PayPal\Api\Payer;
use PayPal\Api\Payment; use PayPal\Api\Payment;
use PayPal\Api\FundingInstrument; use PayPal\Api\FundingInstrument;
use PayPal\Api\Transaction; use PayPal\Api\Transaction;
// ### Credit card token // ### Credit card token
// Saved credit card id from a previous call to // Saved credit card id from a previous call to
// CreateCreditCard.php // CreateCreditCard.php
$creditCardToken = new CreditCardToken(); $creditCardToken = new CreditCardToken();
$creditCardToken->setCreditCardId('CARD-29H07236G1554552FKINPBHQ'); $creditCardToken->setCreditCardId('CARD-17M96700G1952584EKRCTV5Y');
// ### FundingInstrument // ### FundingInstrument
// A resource representing a Payer's funding instrument. // A resource representing a Payer's funding instrument.
// For stored credit card payments, set the CreditCardToken // For stored credit card payments, set the CreditCardToken
// field on this object. // field on this object.
$fi = new FundingInstrument(); $fi = new FundingInstrument();
$fi->setCreditCardToken($creditCardToken); $fi->setCreditCardToken($creditCardToken);
// ### Payer // ### Payer
// A resource representing a Payer that funds a payment // A resource representing a Payer that funds a payment
// For stored credit card payments, set payment method // For stored credit card payments, set payment method
// to 'credit_card'. // to 'credit_card'.
$payer = new Payer(); $payer = new Payer();
$payer->setPaymentMethod("credit_card") $payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi)); ->setFundingInstruments(array($fi));
// ### Itemized information // ### Itemized information
// (Optional) Lets you specify item wise // (Optional) Lets you specify item wise
// information // information
$item1 = new Item(); $item1 = new Item();
$item1->setName('Ground Coffee 40 oz') $item1->setName('Ground Coffee 40 oz')
->setCurrency('USD') ->setCurrency('USD')
->setQuantity(1) ->setQuantity(1)
->setPrice('7.50'); ->setPrice('7.50');
$item2 = new Item(); $item2 = new Item();
$item2->setName('Granola bars') $item2->setName('Granola bars')
->setCurrency('USD') ->setCurrency('USD')
->setQuantity(5) ->setQuantity(5)
->setPrice('2.00'); ->setPrice('2.00');
$itemList = new ItemList(); $itemList = new ItemList();
$itemList->setItems(array($item1, $item2)); $itemList->setItems(array($item1, $item2));
// ### Additional payment details // ### Additional payment details
// Use this optional field to set additional // Use this optional field to set additional
// payment information such as tax, shipping // payment information such as tax, shipping
// charges etc. // charges etc.
$details = new Details(); $details = new Details();
$details->setShipping('1.20') $details->setShipping('1.20')
->setTax('1.30') ->setTax('1.30')
->setSubtotal('17.50'); ->setSubtotal('17.50');
// ### Amount // ### Amount
// Lets you specify a payment amount. // Lets you specify a payment amount.
// You can also specify additional details // You can also specify additional details
// such as shipping, tax. // such as shipping, tax.
$amount = new Amount(); $amount = new Amount();
$amount->setCurrency("USD") $amount->setCurrency("USD")
->setTotal("20.00") ->setTotal("20.00")
->setDetails($details); ->setDetails($details);
// ### Transaction // ### Transaction
// A transaction defines the contract of a // A transaction defines the contract of a
// payment - what is the payment for and who // payment - what is the payment for and who
// is fulfilling it. // is fulfilling it.
$transaction = new Transaction(); $transaction = new Transaction();
$transaction->setAmount($amount) $transaction->setAmount($amount)
->setItemList($itemList) ->setItemList($itemList)
->setDescription("Payment description"); ->setDescription("Payment description");
// ### Payment // ### Payment
// A Payment Resource; create one using // A Payment Resource; create one using
// the above types and intent set to 'sale' // the above types and intent set to 'sale'
$payment = new Payment(); $payment = new Payment();
$payment->setIntent("sale") $payment->setIntent("sale")
->setPayer($payer) ->setPayer($payer)
->setTransactions(array($transaction)); ->setTransactions(array($transaction));
// ###Create Payment // ###Create Payment
// Create a payment by calling the 'create' method // Create a payment by calling the 'create' method
// passing it a valid apiContext. // passing it a valid apiContext.
// (See bootstrap.php for more on `ApiContext`) // (See bootstrap.php for more on `ApiContext`)
// The return object contains the state. // The return object contains the state.
try { try {
$payment->create($apiContext); $payment->create($apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) { } catch (PayPal\Exception\PPConnectionException $ex) {
echo "Exception: " . $ex->getMessage() . PHP_EOL; echo "Exception: " . $ex->getMessage() . PHP_EOL;
var_dump($ex->getData()); var_dump($ex->getData());
exit(1); exit(1);
} }
?> ?>
<html> <html>
<head> <head>
<title>Saved Credit card payments</title> <title>Saved Credit card payments</title>
</head> </head>
<body> <body>
<div> <div>
Created payment: Created payment:
<?php echo $payment->getId();?> <?php echo $payment->getId();?>
</div> </div>
<pre><?php echo $payment->toJSON(JSON_PRETTY_PRINT);?></pre> <pre><?php echo $payment->toJSON(JSON_PRETTY_PRINT);?></pre>
<a href='../index.html'>Back</a> <a href='../index.html'>Back</a>
</body> </body>
</html> </html>

View File

@@ -1,40 +1,42 @@
<?php <?php
// #Execute Payment Sample // #Execute Payment Sample
// This sample shows how you can complete // This sample shows how you can complete
// a payment that has been approved by // a payment that has been approved by
// the buyer by logging into paypal site. // the buyer by logging into paypal site.
// You can optionally update transaction // You can optionally update transaction
// information by passing in one or more transactions. // information by passing in one or more transactions.
// API used: POST '/v1/payments/payment/<payment-id>/execute'. // API used: POST '/v1/payments/payment/<payment-id>/execute'.
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Api\ExecutePayment; use PayPal\Api\ExecutePayment;
use PayPal\Api\Payment; use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution; use PayPal\Api\PaymentExecution;
session_start(); session_start();
if(isset($_GET['success']) && $_GET['success'] == 'true') { if(isset($_GET['success']) && $_GET['success'] == 'true') {
// Get the payment Object by passing paymentId // Get the payment Object by passing paymentId
// payment id was previously stored in session in // payment id was previously stored in session in
// CreatePaymentUsingPayPal.php // CreatePaymentUsingPayPal.php
$paymentId = $_SESSION['paymentId']; $paymentId = $_SESSION['paymentId'];
$payment = Payment::get($paymentId, $apiContext); $payment = Payment::get($paymentId, $apiContext);
// PaymentExecution object includes information necessary // PaymentExecution object includes information necessary
// to execute a PayPal account payment. // to execute a PayPal account payment.
// The payer_id is added to the request query parameters // The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site // when the user is redirected from paypal back to your site
$execution = new PaymentExecution(); $execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']); $execution->setPayerId($_GET['PayerID']);
//Execute the payment //Execute the payment
// (See bootstrap.php for more on `ApiContext`) // (See bootstrap.php for more on `ApiContext`)
$result = $payment->execute($execution, $apiContext); $result = $payment->execute($execution, $apiContext);
echo "<html><body><pre>"; echo "<html><body><pre>";
echo $result->toJSON(JSON_PRETTY_PRINT); echo $result->toJSON(JSON_PRETTY_PRINT);
echo "</pre><a href='../index.html'>Back</a></body></html>"; echo "</pre><a href='../index.html'>Back</a></body></html>";
} else { } else {
echo "User cancelled payment."; echo "<html><body><h1>";
} echo "User cancelled payment.";
echo "</h1><a href='../index.html'>Back</a></body></html>";
}

View File

@@ -1,39 +1,39 @@
<?php <?php
// # GetPaymentSample // # GetPaymentSample
// This sample code demonstrate how you can // This sample code demonstrate how you can
// retrieve a list of all Payment resources // retrieve a list of all Payment resources
// you've created using the Payments API. // you've created using the Payments API.
// Note various query parameters that you can // Note various query parameters that you can
// use to filter, and paginate through the // use to filter, and paginate through the
// payments list. // payments list.
// API used: GET /v1/payments/payments // API used: GET /v1/payments/payments
require __DIR__ . '/../bootstrap.php'; require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Payment; use PayPal\Api\Payment;
$paymentId = "PAY-0XL713371A312273YKE2GCNI"; $paymentId = "PAY-2AH507590P6615624KRCTUSY";
// ### Retrieve payment // ### Retrieve payment
// Retrieve the payment object by calling the // Retrieve the payment object by calling the
// static `get` method // static `get` method
// on the Payment class by passing a valid // on the Payment class by passing a valid
// Payment ID // Payment ID
// (See bootstrap.php for more on `ApiContext`) // (See bootstrap.php for more on `ApiContext`)
try { try {
$payment = Payment::get($paymentId, $apiContext); $payment = Payment::get($paymentId, $apiContext);
} catch (PayPal\Exception\PPConnectionException $ex) { } catch (PayPal\Exception\PPConnectionException $ex) {
echo "Exception:" . $ex->getMessage() . PHP_EOL; echo "Exception:" . $ex->getMessage() . PHP_EOL;
var_dump($ex->getData()); var_dump($ex->getData());
exit(1); exit(1);
} }
?> ?>
<html> <html>
<head> <head>
<title>Lookup a payment</title> <title>Lookup a payment</title>
</head> </head>
<body> <body>
<div>Retrieving Payment ID: <?php echo $paymentId;?></div> <div>Retrieving Payment ID: <?php echo $paymentId;?></div>
<pre><?php echo $payment->toJSON(JSON_PRETTY_PRINT);?></pre> <pre><?php echo $payment->toJSON(JSON_PRETTY_PRINT);?></pre>
<a href='../index.html'>Back</a> <a href='../index.html'>Back</a>
</body> </body>
</html> </html>

View File

@@ -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. ## This is an example configuration file for the SDK.
## The sample scripts configure the SDK dynamically ## The sample scripts configure the SDK dynamically

View File

@@ -11,7 +11,7 @@ use PayPal\Api\CreditCard;
// The cardId can be obtained from a previous save credit // The cardId can be obtained from a previous save credit
// card operation. Use $card->getId() // card operation. Use $card->getId()
$cardId = "CARD-5AR29593TC404090HKIKN77Q"; $cardId = "CARD-44D10970C24287906KRCTWNI";
/// ### Retrieve card /// ### Retrieve card
// (See bootstrap.php for more on `ApiContext`) // (See bootstrap.php for more on `ApiContext`)