/** * @param PayPalHttpConfig $httpConfig * @param string $request * @param mixed $options * @return mixed|void * @throws PayPalConfigurationException * @throws PayPalInvalidCredentialException * @throws PayPalMissingCredentialException */ public function handle($httpConfig, $request, $options) { $credential = $this->apiContext->getCredential(); $config = $this->apiContext->getConfig(); if ($credential == null) { // Try picking credentials from the config file $credMgr = PayPalCredentialManager::getInstance($config); $credValues = $credMgr->getCredentialObject(); if (!is_array($credValues)) { throw new PayPalMissingCredentialException("Empty or invalid credentials passed"); } $credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']); } if ($credential == null || !$credential instanceof OAuthTokenCredential) { throw new PayPalInvalidCredentialException("Invalid credentials passed"); } $httpConfig->setUrl(rtrim(trim($this->_getEndpoint($config)), '/') . (isset($options['path']) ? $options['path'] : '')); // Overwrite Expect Header to disable 100 Continue Issue $httpConfig->addHeader("Expect", null); if (!array_key_exists("User-Agent", $httpConfig->getHeaders())) { $httpConfig->addHeader("User-Agent", PayPalUserAgent::getValue(PayPalConstants::SDK_NAME, PayPalConstants::SDK_VERSION)); } if (!is_null($credential) && $credential instanceof OAuthTokenCredential && is_null($httpConfig->getHeader('Authorization'))) { $httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config), false); } if ($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') { $httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId()); } // Add any additional Headers that they may have provided $headers = $this->apiContext->getRequestHeaders(); foreach ($headers as $key => $value) { $httpConfig->addHeader($key, $value); } }
public function testResetRequestId() { $requestId = $this->apiContext->getrequestId(); $newRequestId = $this->apiContext->resetRequestId(); $this->assertNotNull($newRequestId); $this->assertNotEquals($newRequestId, $requestId); }
/** * @inheritdoc */ private function setConfig() { // ### Api context // Use an ApiContext object to authenticate // API calls. The clientId and clientSecret for the // OAuthTokenCredential class can be retrieved from // developer.paypal.com $this->_apiContext = new ApiContext(new OAuthTokenCredential($this->clientId, $this->clientSecret)); // #### SDK configuration // Comment this line out and uncomment the PP_CONFIG_PATH // 'define' block if you want to use static file // based configuration $this->_apiContext->setConfig(ArrayHelper::merge(['mode' => self::MODE_SANDBOX, 'http.ConnectionTimeOut' => 30, 'http.Retry' => 1, 'log.LogEnabled' => YII_DEBUG ? 1 : 0, 'log.FileName' => Yii::getAlias('@runtime/logs/paypal.log'), 'log.LogLevel' => self::LOG_LEVEL_FINE, 'validation.level' => 'log', 'cache.enabled' => 'true'], $this->config)); // Set file name of the log if present if (isset($this->config['log.FileName']) && isset($this->config['log.LogEnabled']) && (bool) $this->config['log.LogEnabled'] == true) { $logFileName = \Yii::getAlias($this->config['log.FileName']); if ($logFileName) { if (!file_exists($logFileName)) { if (!touch($logFileName)) { throw new ErrorException('Can\'t create paypal.log file at: ' . $logFileName); } } } $this->config['log.FileName'] = $logFileName; } return $this->_apiContext; }
/** * Handle * * @param \PayPal\Core\PPHttpConfig $httpConfig * @param \PayPal\Core\PPRequest $request * @param array $options * * @throws \PayPal\Exception\PPInvalidCredentialException * @throws \PayPal\Exception\PPMissingCredentialException */ public function handle($httpConfig, $request, $options) { $credential = $this->apiContext->getCredential(); $config = $this->apiContext->getConfig(); if ($credential == null) { // Try picking credentials from the config file $credMgr = PPCredentialManager::getInstance($config); $credValues = $credMgr->getCredentialObject(); if (!is_array($credValues)) { throw new PPMissingCredentialException("Empty or invalid credentials passed"); } $credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']); } if ($credential == null || !$credential instanceof OAuthTokenCredential) { throw new PPInvalidCredentialException("Invalid credentials passed"); } $httpConfig->setUrl(rtrim(trim($this->_getEndpoint($config)), '/') . (isset($options['path']) ? $options['path'] : '')); if (!array_key_exists("User-Agent", $httpConfig->getHeaders())) { $httpConfig->addHeader("User-Agent", PPUserAgent::getValue(self::$sdkName, self::$sdkVersion)); } if (!is_null($credential) && $credential instanceof OAuthTokenCredential) { $httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config)); } if ($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') { $httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId()); } }
function getApiContext($clientId, $clientSecret) { // #### SDK configuration // Register the sdk_config.ini file in current directory // as the configuration source. /* if(!defined("PP_CONFIG_PATH")) { define("PP_CONFIG_PATH", __DIR__); } */ // ### Api context // Use an ApiContext object to authenticate // API calls. The clientId and clientSecret for the // OAuthTokenCredential class can be retrieved from // developer.paypal.com $apiContext = new ApiContext(new OAuthTokenCredential($clientId, $clientSecret)); // Comment this line out and uncomment the PP_CONFIG_PATH // 'define' block if you want to use static file // based configuration $apiContext->setConfig(array('mode' => 'sandbox', 'log.LogEnabled' => true, 'log.FileName' => APPLICATION_PATH . '/../logs/PayPal.log', 'log.LogLevel' => 'FINE', 'validation.level' => 'log', 'cache.enabled' => true)); // Partner Attribution Id // Use this header if you are a PayPal partner. Specify a unique BN Code to receive revenue attribution. // To learn more or to request a BN Code, contact your Partner Manager or visit the PayPal Partner Portal // $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', '123123123'); return $apiContext; }
public function getApiContext($clientId, $clientSecret) { $oauthCredentials = new OAuthTokenCredential($clientId, $clientSecret); $apiContext = new ApiContext($oauthCredentials); $apiContext->setConfig($this->config); return $apiContext; }
/** * Helper method for getting an APIContext for all calls * * @return PayPal\Rest\ApiContext */ function getApiContext() { // ### Api context // Use an ApiContext object to authenticate // API calls. The clientId and clientSecret for the // OAuthTokenCredential class can be retrieved from // developer.paypal.com /* // sandbox $apiContext = new ApiContext( new OAuthTokenCredential( 'AafDsxDBf3aFlXShFlPBWjIYLWlpffOjQ_YVySCcGBrAWsgfJaJ_TJiszPi7', 'EE2lCxCSyGfI8TPKHRPALfhxcBfqWk6UBeyLSGtLLJWEYSo0xJOsxtApcFd_' ) ); */ // live $apiContext = new ApiContext(new OAuthTokenCredential('AXh7hxAI5NHnEklbfdA9vJsYRZy1U2u5HfcELrXlPyMSNCJAQ7D6UBaLI8jc', 'EDGVlhCrtFADL5v3CJz-ejRchN8PvYrotuwiMM-ds9BVEXQP5LlNsBZW2hA6')); // #### SDK configuration // Comment this line out and uncomment the PP_CONFIG_PATH // 'define' block if you want to use static file // based configuration $apiContext->setConfig(array('mode' => 'live', 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => true, 'log.FileName' => '../PayPal.log', 'log.LogLevel' => 'FINE')); /* // Register the sdk_config.ini file in current directory // as the configuration source. if(!defined("PP_CONFIG_PATH")) { define("PP_CONFIG_PATH", __DIR__); } */ return $apiContext; }
/** * @param PaymentInterface $payment * @throws InvalidPaymentException */ public function check(PaymentInterface $payment) { if ($payment->getTransaction()) { throw new InvalidPaymentException('Payment has already been received.'); } $credentials = new OAuthTokenCredential($this->options['client_id'], $this->options['secret']); $apiContext = new ApiContext($credentials); $apiContext->setConfig(['mode' => $this->options['mode']]); $paypalPayment = Payment::get($payment->getExtraData('paypal_payment_id'), $apiContext); $payer = $paypalPayment->getPayer(); if (!$payer || 'verified' !== strtolower($payer->getStatus())) { throw new InvalidPaymentException('Payer not verified.'); } if ('created' == $paypalPayment->getState()) { $execution = new PaymentExecution(); $execution->setPayerId($paypalPayment->getPayer()->getPayerInfo()->getPayerId()); $paypalPayment->execute($execution, $apiContext); } if ('approved' != $paypalPayment->getState()) { throw new InvalidPaymentException('Invalid payment state.'); } $math = new NativeMath(); $controlSum = 0; foreach ($paypalPayment->getTransactions() as $transaction) { if ($transaction->getAmount()->getCurrency() != $payment->getAccount()->getCurrency()) { throw new InvalidPaymentException('Invalid payment currency.'); } $controlSum = $math->sum($controlSum, $transaction->getAmount()->getTotal()); } if (!$math->eq($payment->getPaymentSum(), $controlSum)) { throw new InvalidPaymentException('Invalid payment sum.'); } }
/** * @dataProvider modeProvider * @param $configs */ public function testGetEndpoint($configs) { $config = $configs + array('cache.enabled' => true, 'http.headers.header1' => 'header1value'); $this->apiContext->setConfig($config); $this->httpConfig = new PayPalHttpConfig(null, 'POST', $config); $this->handler = new OauthHandler($this->apiContext); $this->handler->handle($this->httpConfig, null, $this->config); }
/** * Set api context * * @param $website * @return $this */ public function setApiContext($website = null) { $this->_apiContext = new ApiContext(new OAuthTokenCredential(Mage::getStoreConfig('iways_paypalplus/api/client_id', $website), Mage::getStoreConfig('iways_paypalplus/api/client_secret', $website))); $this->_mode = Mage::getStoreConfig('iways_paypalplus/api/mode', $website); $this->_apiContext->setConfig(array('http.ConnectionTimeOut' => 30, 'http.Retry' => 1, 'mode' => $this->_mode, 'log.LogEnabled' => Mage::getStoreConfig('dev/log/active', $website), 'log.FileName' => Mage::getBaseDir('log') . DS . 'PayPal.log', 'log.LogLevel' => 'INFO')); $this->_apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', 'Magento_Cart_PayPalPlus'); return $this; }
/** * Returns the URL to which the user must be redirected to * logout from the OpenID provider (i.e. PayPal) * * @param string $redirectUri Uri on merchant website to where * the user must be redirected to post logout * @param string $idToken id_token from the TokenInfo object * @param ApiContext $apiContext Optional API Context * @return string logout URL */ public static function getLogoutUrl($redirectUri, $idToken, $apiContext = null) { if (is_null($apiContext)) { $apiContext = new ApiContext(); } $config = $apiContext->getConfig(); $params = array('id_token' => $idToken, 'redirect_uri' => $redirectUri, 'logout' => 'true'); return sprintf("%s/webapps/auth/protocol/openidconnect/v1/endsession?%s", self::getBaseUrl($config), http_build_query($params)); }
public function getApiContext() { /*$apiContext = new ApiContext(new OAuthTokenCredential( 'AbxhksgjlQREXW6DXFywwhHj-WYBZKojDMc1il3WlpF7OU_yR8R7J8pZKOP1PT5f4UP7OXFoCHO4L-Zq', 'ELp7381HZADMafiEvmpTiIsuEzQEhNvm3WTcA6n-kiAg4MvSoCei4Ob0jikeekgcIsXSHTS0cBf1-TVG' ));*/ $apiContext = new ApiContext(new OAuthTokenCredential('AViZLEV_4q3zxbXnCZkorEW_ZQjjBaMBveSt0EZHoNEicnFarwU1GXvRh0xx-ZBqfFgNTVKiYgMnTySM', 'EJybFEJ8EOhrAeo93llf3u-SwLSeIhVk2LFPZCsGp_VLumj0gRA4hwRgOhWFaU1tLBo_eDdt1E_Jzeus')); $apiContext->setConfig(array('http.ConnectionTimeOut' => 30, 'http.Retry' => 1, 'mode' => 'live', 'log.LogEnabled' => true, 'log.FileName' => '../PayPal.log', 'log.LogLevel' => 'INFO')); return $apiContext; }
public function get_api_context() { if (PAYPAL_MODE == 'sandbox') { $apiContext = new ApiContext(new OAuthTokenCredential(PAYPAL_DEVID, PAYPAL_DEVSECRET)); } else { $apiContext = new ApiContext(new OAuthTokenCredential(PAYPAL_LIVEID, PAYPAL_LIVESECRET)); } $apiContext->setConfig(array('mode' => PAYPAL_MODE, 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => true, 'log.FileName' => 'app/PayPal.log', 'log.LogLevel' => 'FINE')); return $apiContext; }
public function getPayPal() { if (!$this->payPalClientId) { throw new RuntimeException('Paypal clientId is missing'); } if (!$this->payPalClientSecret) { throw new RuntimeException('Paypal clientSecret is missing'); } $apiContext = new ApiContext(new OAuthTokenCredential($this->payPalClientId, $this->payPalClientSecret)); $apiContext->setConfig(array('mode' => $this->developmentMode ? 'sandbox' : 'live', 'log.LogEnabled' => true, 'log.FileName' => '/tmp/PayPal.log', 'log.LogLevel' => $this->developmentMode ? 'DEBUG' : 'FINE', 'cache.enabled' => true, 'cache.FileName' => 'data/paypal.cache')); return $apiContext; }
private function getApiContext($clientId, $clientSecret) { global $tmpdir, $config; $payconf = $config['PayPal']; if ($payconf['enable'] === 'no') { echo "FATAL ERROR: PayPal not configured."; exit(2); } $apiContext = new ApiContext(new OAuthTokenCredential($clientId, $clientSecret)); $apiContext->setConfig(array('mode' => $payconf['enable'] == 'prod' ? 'live' : 'sandbox', 'log.LogEnabled' => false, 'log.FileName' => $tmpdir . '/PayPal.log', 'log.LogLevel' => 'INFO', 'cache.enabled' => true, 'cache.FileName' => $tmpdir . 'paypal.cache')); return $apiContext; }
public static function SetUpForFunctionalTests(\PHPUnit_Framework_TestCase &$test) { $context = new ApiContext(); $context->setConfig(array('mode' => 'sandbox', 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => true, 'log.FileName' => '../PayPal.log', 'log.LogLevel' => 'FINE', 'validation.level' => 'warning')); PayPalCredentialManager::getInstance()->setCredentialObject(PayPalCredentialManager::getInstance()->getCredentialObject('acct1')); self::$mode = getenv('REST_MODE') ? getenv('REST_MODE') : 'mock'; if (self::$mode != 'sandbox') { // Mock PayPalRest Caller if mode set to mock $test->mockPayPalRestCall = $test->getMockBuilder('\\PayPal\\Transport\\PayPalRestCall')->disableOriginalConstructor()->getMock(); $test->mockPayPalRestCall->expects($test->any())->method('execute')->will($test->returnValue($test->response)); } }
public static function getApiContext() { // ### Api context // Use an ApiContext object to authenticate // API calls. The clientId and clientSecret for the // OAuthTokenCredential class can be retrieved from // developer.paypal.com $apiContext = new ApiContext(new OAuthTokenCredential($_ENV['PAYPAL_CLIENT_ID'], $_ENV['PAYPAL_SECRET'])); // setting some configurations $apiContext->setConfig(array('mode' => $_ENV['PAYPAL_MODE'], 'log.LogEnabled' => true, 'log.FileName' => base_path('storage/logs/paypal.log'), 'log.LogLevel' => 'DEBUG', 'cache.enabled' => true)); return $apiContext; }
/** * @param PayPalHttpConfig $httpConfig * @param string $request * @param mixed $options * @return mixed|void * @throws PayPalConfigurationException * @throws PayPalInvalidCredentialException * @throws PayPalMissingCredentialException */ public function handle($httpConfig, $request, $options) { $config = $this->apiContext->getConfig(); $httpConfig->setUrl(rtrim(trim($this->_getEndpoint($config)), '/') . (isset($options['path']) ? $options['path'] : '')); $headers = array("User-Agent" => PayPalUserAgent::getValue(PayPalConstants::SDK_NAME, PayPalConstants::SDK_VERSION), "Authorization" => "Basic " . base64_encode($options['clientId'] . ":" . $options['clientSecret']), "Accept" => "*/*"); $httpConfig->setHeaders($headers); // Add any additional Headers that they may have provided $headers = $this->apiContext->getRequestHeaders(); foreach ($headers as $key => $value) { $httpConfig->addHeader($key, $value); } }
/** * Getting the API context for the application * change the clientID and clientSecret accordingly * * @return boolean */ public static function getApiContext() { // setting api codes $client_id = "AY1PlRC0yK6SExlx8aRDW-hF2REkl90Qmza0Ak5LUacd-LFAczGmXfanQYK-"; $client_secret = "EBXUZxD6PobEUtc-WldtZgbG8eUzl4IkOFAeMxpAGhNDt-mESoj3a3QRRIGw"; // getting the ApiContext from oauths $api_context = new ApiContext(new OAuthTokenCredential($client_id, $client_secret)); // setting api contextd $api_context->setConfig(array('mode' => 'sandbox', 'http.ConnectionTimeOut' => 30, 'log.LogEnabled' => true, 'log.FileName' => '../PayPal.log', 'log.LogLevel' => 'FINE', 'validation.level' => 'log', 'cache.enabled' => 'true')); // returning api context return $api_context; }
public function testGetAccessTokenUnit() { $config = array('mode' => 'sandbox', 'cache.enabled' => true, 'cache.FileName' => AuthorizationCacheTest::CACHE_FILE); $cred = new OAuthTokenCredential('clientId', 'clientSecret'); //{"clientId":{"clientId":"clientId","accessToken":"accessToken","tokenCreateTime":1421204091,"tokenExpiresIn":288000000}} AuthorizationCache::push($config, 'clientId', $cred->encrypt('accessToken'), 1421204091, 288000000); $apiContext = new ApiContext($cred); $apiContext->setConfig($config); $this->assertEquals('clientId', $cred->getClientId()); $this->assertEquals('clientSecret', $cred->getClientSecret()); $result = $cred->getAccessToken($config); $this->assertNotNull($result); }
/** * @param $environment * @return ApiContext */ public function changeEnvironment($environment) { $endpoint = ''; switch ($environment) { case GeneralConst::ENVIRONMENT_SANDBOX: $endpoint = GeneralConst::ENDPOING_SANDBOX; break; case GeneralConst::ENVIRONMENT_PROD: $endpoint = GeneralConst::ENDPOINT_PROD; break; } $config['service.EndPoint'] = $endpoint; $config['mode'] = $environment; $this->apiContext->setConfig($config); return $this->apiContext; }
private function setApiContext() { $settings = ClientHelper::getPaymentGatewayInfo('paypal'); $client_id = $settings->sandbox_mode ? $settings->test_client_id : $settings->client_id; $secret = $settings->sandbox_mode ? $settings->test_secret : $settings->secret; $this->apiContext = new ApiContext(new OAuthTokenCredential($client_id, $secret)); $this->apiContext->setConfig(['mode' => $settings->sandbox_mode ? 'sandbox' : 'live', 'log.FileName' => './storage/logs/paypal.log', 'log.LogLevel' => $settings->sandbox_mode ? 'DEBUG' : 'INFO', 'cache.enabled' => false]); }
protected function apiContext() { $credential = new OAuthTokenCredential($this->get_config('PAYPAL_CLIENT_ID_' . strtoupper($this->get_config('PAYPAL_MODE'))), $this->get_config('PAYPAL_SECRET_' . strtoupper($this->get_config('PAYPAL_MODE')))); $credential::$expiryBufferTime = defined('SESSION_LIFE_CUSTOMERS') ? SESSION_LIFE_CUSTOMERS : 1440; $apiContext = new ApiContext($credential); $auth_cache_file = SQL_CACHEDIR . 'pp_auth_' . $this->get_config('PAYPAL_MODE') . '.cache'; if (!is_file($auth_cache_file)) { file_put_contents($auth_cache_file, ''); } $apiContext->setConfig(array('mode' => $this->get_config('PAYPAL_MODE'), 'log.LogEnabled' => $this->get_config('PAYPAL_LOG_ENALBLED') == '1' ? true : false, 'log.FileName' => DIR_FS_LOG . 'mod_paypal_' . $this->get_config('PAYPAL_MODE') . '_' . date('Y-m-d') . '.log', 'log.LogLevel' => $this->loglevel, 'validation.level' => 'log', 'cache.enabled' => is_writeable(SQL_CACHEDIR) ? true : false, 'cache.FileName' => $auth_cache_file)); if (strpos($this->code, 'paypalplus') !== false) { $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', 'ModifiedeCommerce_Cart_REST_Plus'); } else { $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', 'ModifiedeCommerce_Cart_REST_EC'); } return $apiContext; }
/** * Execute the console command. * * @return mixed */ public function handle() { if (Config::get("customer_portal.paypal_enabled") !== true) { $this->error("PayPal is not enabled in the customer portal configuration."); return; } $apiContext = new ApiContext(new OAuthTokenCredential(Config::get("customer_portal.paypal_api_client_id"), Config::get("customer_portal.paypal_api_client_secret"))); $apiContext->setConfig(['mode' => 'live', 'log.LogEnabled' => true, 'log.FileName' => storage_path("logs/paypal.log"), 'log.LogLevel' => 'ERROR']); try { Webhook::getAll($apiContext); } catch (Exception $e) { $this->error("Credentials failed! Please make sure this is a LIVE account and not a SANDBOX account and try again."); $this->error("Specific error was: {$e->getMessage()}"); return; } $this->info("Credentials tested successfully."); }
private function get_credentials($teacherID) { if ($teacherID == null) { $teacherID = "default"; } $go_live = true; $file_content = file_get_contents(APPPATH . '/../../paypal_credentials.json'); $all_credentials = json_decode($file_content, true); $teacher_credentials = $all_credentials[$teacherID]; $credentials = $teacher_credentials[$go_live ? 'live' : 'sandbox']; $apiContext = new ApiContext(new OAuthTokenCredential($credentials['clientID'], $credentials['clientSecret'])); // print_r($apiContext); // To make the service live! if ($go_live) { $apiContext->setConfig(array('mode' => 'live')); } return $apiContext; }
/** * @inheritdoc */ private function setConfig() { $this->_apiContext = new ApiContext(new OAuthTokenCredential($this->clientId, $this->clientSecret)); $logFileName = \Yii::getAlias('@runtime/logs/paypal.log'); if (isset($this->config['log.FileName']) && isset($this->config['log.LogEnabled']) && $this->config['log.LogEnabled']) { $logFileName = \Yii::getAlias($this->config['log.FileName']); if ($logFileName) { if (!file_exists($logFileName)) { if (!touch($logFileName)) { throw new ErrorException($logFileName . ' for paypal not created!'); } } } $this->config['log.FileName'] = $logFileName; } $this->_apiContext->setConfig(ArrayHelper::merge(['mode' => self::MODE_SANDBOX, 'http.ConnectionTimeOut' => 30, 'http.Retry' => 1, 'log.LogEnabled' => YII_DEBUG ? 1 : 0, 'log.FileName' => $logFileName, 'log.LogLevel' => self::LOG_LEVEL_FINE, 'validation.level' => 'log', 'cache.enabled' => 'true'], $this->config)); return $this->_apiContext; }
/** * @param array $handlers Array of handlers * @param string $path Resource path relative to base service endpoint * @param string $method HTTP method - one of GET, POST, PUT, DELETE, PATCH etc * @param string $data Request payload * @param array $headers HTTP headers * @return mixed * @throws \PayPal\Exception\PayPalConnectionException */ public function execute($handlers = array(), $path, $method, $data = '', $headers = array()) { $config = $this->apiContext->getConfig(); $httpConfig = new PayPalHttpConfig(null, $method, $config); $headers = $headers ? $headers : array(); $httpConfig->setHeaders($headers + array('Content-Type' => 'application/json')); /** @var \Paypal\Handler\IPayPalHandler $handler */ foreach ($handlers as $handler) { if (!is_object($handler)) { $fullHandler = "\\" . (string) $handler; $handler = new $fullHandler($this->apiContext); } $handler->handle($httpConfig, $data, array('path' => $path, 'apiContext' => $this->apiContext)); } $connection = new PayPalHttpConnection($httpConfig, $config); $response = $connection->execute($data); return $response; }
/** * Helper method for getting an APIContext for all calls * @return ApiContext */ function getApiContext() { // ### Api context // Use an ApiContext object to authenticate // API calls. The clientId and clientSecret for the // OAuthTokenCredential class can be retrieved from // developer.paypal.com $apiContext = new ApiContext(new OAuthTokenCredential($this->clientId, $this->clientSecret)); // Comment this line out and uncomment the PP_CONFIG_PATH // 'define' block if you want to use static file // based configuration $apiContext->setConfig(array('mode' => $this->mode, 'log.LogEnabled' => true, 'log.FileName' => $this->logfile, 'log.LogLevel' => 'DEBUG', 'cache.enabled' => true)); // Partner Attribution Id // Use this header if you are a PayPal partner. Specify a unique BN Code to receive revenue attribution. // To learn more or to request a BN Code, contact your Partner Manager or visit the PayPal Partner Portal // $apiContext->addRequestHeader('PayPal-Partner-Attribution-Id', '123123123'); return $this->apiContext = $apiContext; }
public function callExecute($clientId, $clientSecret, $paymentId, $payerId, $amount, $currency) { $oauthCredential = new OAuthTokenCredential($clientId, $clientSecret); $apiContext = new ApiContext($oauthCredential); $apiContext->setConfig(['mode' => $this->mode]); $payment = Payment::get($paymentId, $apiContext); $execution = new PaymentExecution(); $execution->setPayerId($payerId); $result = $payment->execute($execution, $apiContext); try { $payment = Payment::get($paymentId, $apiContext); } catch (\Exception $e) { throw new PaymentException('unable to find payment: ' . $e->getMessage()); } if ($payment->state == 'approved') { return true; } return false; }
public function order() { $paypalConf = $this->config->item('paypal'); $clientId = $paypalConf['clientId']; $clientSecret = $paypalConf['clientSecret']; $appName = $paypalConf['appName']; $price = $paypalConf['price']; $shiping = 0; $tax = 0; $mode = "sandbox"; //or live $apiContext = new ApiContext(new OAuthTokenCredential($clientId, $clientSecret)); $apiContext->setConfig(array('mode' => $mode, 'log.LogEnabled' => false)); $payer = new Payer(); $payer->setPaymentMethod("paypal"); $item1 = new Item(); $item1->setName($appName)->setCurrency('USD')->setQuantity(1)->setPrice($price); $itemList = new ItemList(); $itemList->setItems(array($item1)); $details = new Details(); $details->setShipping($shiping)->setTax($tax)->setSubtotal($price); $amount = new Amount(); $amount->setCurrency("USD")->setTotal($price + $shiping + $tax)->setDetails($details); $transaction = new Transaction(); $transaction->setAmount($amount)->setItemList($itemList)->setDescription("Payment description")->setInvoiceNumber(uniqid()); $token = $this->createToken(); $baseUrl = getBaseUrl(); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("{$baseUrl}/paypal/ordersucess?success=true&tk1=" . $token[0] . "&tk2=" . $token[1])->setCancelUrl("{$baseUrl}/paypal/orderfailed?success=false"); $payment = new Payment(); $payment->setIntent("order")->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions(array($transaction)); // For Sample Purposes Only. $request = clone $payment; try { $payment->create($apiContext); } catch (Exception $ex) { // NOTE: PLEASE DO NOT USE RESULTPRINTER CLASS IN YOUR ORIGINAL CODE. FOR SAMPLE ONLY ResultPrinter::printError("Created Payment Order Using PayPal. Please visit the URL to Approve.", "Payment", null, $request, $ex); exit(1); } $approvalUrl = $payment->getApprovalLink(); header("Location: " . $approvalUrl . ""); die; }