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
* @return $this
*/
public function create($apiContext = null, $correlationId = null) {
public function create($apiContext = null, $correlationId = null)
{
if ($apiContext == null) {
$apiContext = new ApiContext(self::$credential);
}
@@ -45,4 +46,31 @@ class FuturePayment extends Payment
return $this;
}
/**
* Get a Refresh Token from Authorization Code
*
* @param $authorizationCode
* @param ApiContext $apiContext
* @return string|null refresh token
*/
public static function getRefreshToken($authorizationCode, $apiContext = null)
{
$apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
$credential = $apiContext->getCredential();
return $credential->getRefreshToken($apiContext->getConfig(), $authorizationCode);
}
/**
* Updates Access Token using long lived refresh token
*
* @param string|null $refreshToken
* @param ApiContext $apiContext
* @return void
*/
public function updateAccessToken($refreshToken, $apiContext)
{
$apiContext = $apiContext ? $apiContext : new ApiContext(self::$credential);
$apiContext->getCredential()->updateAccessToken($apiContext->getConfig(), $refreshToken);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -70,6 +70,11 @@ class PPLoggingManager
*/
public function __construct()
{
// To suppress the warning during the date() invocation in logs, we would default the timezone to GMT.
if (!ini_get('date.timezone')) {
date_default_timezone_set('GMT');
}
$config = PPConfigManager::getInstance()->getConfigHashmap();
$this->isLoggingEnabled = (array_key_exists('log.LogEnabled', $config) && $config['log.LogEnabled'] == '1');
@@ -93,7 +98,7 @@ class PPLoggingManager
private function log($message, $level = PPLoggingLevel::INFO)
{
if ($this->isLoggingEnabled && ($level <= $this->loggingLevel)) {
error_log($this->loggerName . ": $message\n", 3, $this->loggerFile);
error_log("[" . date('d-m-Y h:i:s') . "] " . $this->loggerName . ": $message\n", 3, $this->loggerFile);
}
}

View File

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

View File

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

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",
"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>
<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()
-&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;setLastName(<span class="hljs-string">"Doctor"</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>;
<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
static <code>get</code> method
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
on the Invoice class by passing a valid
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
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();

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
on the Invoice class by passing a valid
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
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>) {

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.
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">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">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">Transaction</span>;
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>)
-&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
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>)
-&gt;setPayer(<span class="hljs-variable">$payer</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>
<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
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
passing it a valid apiContext.
(See bootstrap.php for more on <code>ApiContext</code>)
The return object contains the state and the
url to which the buyer must be redirected to
for payment approval
Please note that currently future payments works only with Paypal as a funding instrument.</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">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>
<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();
<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.
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();

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-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-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">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">"&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>

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>;
<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
static <code>get</code> method
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 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
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-variable">$card</span> = CreditCard::get(<span class="hljs-variable">$cardId</span>, <span class="hljs-variable">$apiContext</span>);

View File

@@ -360,6 +360,50 @@
</li>
</ul>
</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> <!-- /container -->

View File

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

View File

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

View File

@@ -16,7 +16,7 @@ try {
// on the Invoice class by passing a valid
// Invoice ID
// (See bootstrap.php for more on `ApiContext`)
$invoice = Invoice::get("INV2-9CAH-K5G7-2JPL-G4B4", $apiContext);
$invoice = Invoice::get("INV2-W4LC-6QS9-JZ62-VE4P", $apiContext);
// ### Notification Object
// This would send a notification to both merchant as well

View File

@@ -15,7 +15,7 @@ try {
// on the Invoice class by passing a valid
// Invoice ID
// (See bootstrap.php for more on `ApiContext`)
$invoice = Invoice::get("INV2-9DRB-YTHU-2V9Q-7Q24", $apiContext);
$invoice = Invoice::get("INV2-W4LC-6QS9-JZ62-VE4P", $apiContext);
// ### Send Invoice
// Send a legitimate invoice to the payer

View File

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

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

View File

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

View File

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

View File

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

View File

@@ -1,40 +1,42 @@
<?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') {
// Get the payment Object by passing paymentId
// payment id was previously stored in session in
// CreatePaymentUsingPayPal.php
$paymentId = $_SESSION['paymentId'];
$payment = Payment::get($paymentId, $apiContext);
// PaymentExecution object includes information necessary
// to execute a PayPal account payment.
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']);
//Execute the payment
// (See bootstrap.php for more on `ApiContext`)
$result = $payment->execute($execution, $apiContext);
echo "<html><body><pre>";
echo $result->toJSON(JSON_PRETTY_PRINT);
echo "</pre><a href='../index.html'>Back</a></body></html>";
} else {
echo "User cancelled payment.";
}
<?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') {
// Get the payment Object by passing paymentId
// payment id was previously stored in session in
// CreatePaymentUsingPayPal.php
$paymentId = $_SESSION['paymentId'];
$payment = Payment::get($paymentId, $apiContext);
// PaymentExecution object includes information necessary
// to execute a PayPal account payment.
// The payer_id is added to the request query parameters
// when the user is redirected from paypal back to your site
$execution = new PaymentExecution();
$execution->setPayerId($_GET['PayerID']);
//Execute the payment
// (See bootstrap.php for more on `ApiContext`)
$result = $payment->execute($execution, $apiContext);
echo "<html><body><pre>";
echo $result->toJSON(JSON_PRETTY_PRINT);
echo "</pre><a href='../index.html'>Back</a></body></html>";
} else {
echo "<html><body><h1>";
echo "User cancelled payment.";
echo "</h1><a href='../index.html'>Back</a></body></html>";
}

View File

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