Uncaught PPConnectionException Http response code 400 - php

Basically what I can see is that I am failing to create the apiContext object. Can anyone see where the error is? Please tell me how I can improve the question.
Here is the error:
Fatal error: Uncaught exception 'PayPal\Exception\PPConnectionException'
with message 'Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.' in /vendor/paypal
/sdk-core-php/lib/PayPal/Core/PPHttpConnection.php:104 Stack trace: #0
/vendor/paypal/sdk-core-php/lib/PayPal/Transport/PPRestCall.php(44):
PayPal\Core\PPHttpConnection->execute('{"intent":"sale...') #1 /vendor/paypal
/rest-api-sdk-php/lib/PayPal/Api/Payment.php(246): PayPal\Transport
\PPRestCall->execute(Array, '/v1/payments/pa...', 'POST',
'{"intent":"sale...') #2 /pymt.php(38): PayPal\Api
\Payment->create(Object(PayPal\Rest\ApiContext)) #3 {main} thrown in /vendor
/paypal/sdk-core-php/lib/PayPal/Core/PPHttpConnection.php on line 104
This is the PHP sample I'm using. I am trying to run it off my server. If a customer clicks the pay with paypal button, it runs the following sample script:
<?php
require __DIR__ . '/../bootstrap.php';
use PayPal\Api\Address;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\FundingInstrument;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
session_start();
$payer = new Payer();
$payer->setPayment_method('paypal');
$amount = new Amount();
$amount->setCurrency('USD');
$amount->setTotal('1.00');
$transaction = new Transaction();
$transaction->setAmount($amount);
$transaction->setDescription('This is the payment description.');
$baseUrl = getBaseUrl();
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturn_url('baseUrl/sale.php');
$redirectUrls->setCancel_url('baseUrl/saleFail.php');
$payment = new Payment();
$payment->setIntent('sale');
$payment->setPayer($payer);
$payment->setRedirect_urls($redirectUrls);
$payment->setTransactions(array($transaction));
try {
$payment->create($apiContext);
} catch (\PPConnectionException $ex) {
echo 'Exception: ' . $ex->getMessage() . PHP_EOL;
var_dump($ex->getData());
exit(1);
}
foreach ($payment->getLinks() as $link) {
if ($link->getRel() == 'approval_url') {
$redirectUrl = $link->getHref();
}
}
$_SESSION['paymentId'] = $payment->getId();
if(isset($redirectUrl)) {
header('Location: $redirectUrl');
exit;
}
Here's the redacted bootstrap.php:
<?php
/*
* Sample bootstrap file.
*/
// Include the composer autoloader
if(!file_exists(__DIR__ .'/vendor/autoload.php')) {
echo "The 'vendor' folder is missing. You must run 'composer update --no-dev' to resolve application dependencies.\nPlease see the README for more information.\n";
exit(1);
}
require __DIR__ . '/vendor/autoload.php';
require __DIR__ . '/common.php';
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
$apiContext = getApiContext();
/**
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
$apiContext = new ApiContext(
new OAuthTokenCredential(
'MY CLIENT ID',
'MY SECRET'
)
);
// 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;
}
Can anyone help? Let me know if you need more info. Thanks up front.

I got the same problem too, I found that if any param was wrong (for example: an invalid card number or a invalid currency format), php SDK throw Connection Exception, Instead of returning certain Json Message(when I organize POST data myself and send with curl , It's OK)! I wander if it is reasonable to design like this, Or we just missed something!...

Related

HelloSign PHP SDK - Class "HelloSignSDK\Configuration" not found

I tried with the below code to get the Account details, it's working fine.
require_once __DIR__ . "/vendor/autoload.php";
$apikey = "<API KEY FROM HELLOSIGN>";
$client = new HelloSign\Client($apikey);
$account = $client->getAccount();
But when I try with the below code to get an Account using SDK, reference link: https://developers.hellosign.com/api/reference/operation/accountGet/:
require_once __DIR__ . "/vendor/autoload.php";
$config = HelloSignSDK\Configuration::getDefaultConfiguration();
// Configure HTTP basic authorization: api_key
$config->setUsername("YOUR_API_KEY");
// or, configure Bearer (JWT) authorization: oauth2
// $config->setAccessToken("YOUR_ACCESS_TOKEN");
$api = new HelloSignSDK\Api\AccountApi($config);
try {
$result = $api->accountGet(null, 'jack#example.com');
print_r($result);
} catch (HelloSignSDK\ApiException $e) {
$error = $e->getResponseObject();
echo "Exception when calling HelloSign API: "
. print_r($error->getError());
}
It throws an error: Fatal error: Uncaught Error: Class "HelloSignSDK\Configuration" not found
Added autoload, why is this issue if using SDK? Kindly help!

Paypal 500 Error: javax.validation.ValidationException

On my first attempt to use PayPal's REST Api, I ran into a 500 error. I googled around a bit and wasn't able to find much helpful information on PayPal 500 errors, and I have no idea what would cause it.
The error is as follows.
500
javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.[java.lang.NullPointerException]
exception 'PayPal\Exception\PayPalConnectionException' with message 'Got Http response code 500 when accessing https://api.sandbox.paypal.com/v1/payments/payment.' in /home/user/public_html/sandbox/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php:154
Stack trace:
#0 /home/user/public_html/sandbox/vendor/paypal/rest-api-sdk-php/lib/PayPal/Transport/PayPalRestCall.php(73): PayPal\Core\PayPalHttpConnection->execute('{"intent":"sale...')
#1 /home/user/public_html/sandbox/vendor/paypal/rest-api-sdk-php/lib/PayPal/Common/PayPalResourceModel.php(102): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/payments/pa...', 'POST', '{"intent":"sale...', NULL)
#2 /home/user/public_html/sandbox/vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Payment.php(565): PayPal\Common\PayPalResourceModel::executeCall('/v1/payments/pa...', 'POST', '{"intent":"sale...', NULL, Object(PayPal\Rest\ApiContext), NULL)
#3 /home/user/public_html/sandbox/checkout.php(41): PayPal\Api\Payment->create(Object(PayPal\Rest\ApiContext))
#4 {main}
I also was unable to find a way to get a more verbose error message.
My code :
<?php
use PayPal\Api\Payer;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Details;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
//include 'app.php';
require __DIR__ . '/vendor/autoload.php';
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'AfynNvA-2KwijS3pZ56jFPZwMxvObkwav8Vk4HMLc2foLahtCTPqzd_wfgt_wBtOCqqhLyk95T8LFUe0', // ClientID
'REDACTED' // ClientSecret
)
);
$price = 12;
$product = "Test";
$shipping = 0;
$total = $price + $shipping;
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$item = new Item();
$item->setName($product)->setCurrency('USD')->setQuantity(1)->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details->setShipping($shipping)->setSubtotal($price);
$amount = new Amount();
$amount->setCurrency('USD')->setTotal($total)->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)->setItemList($itemList)->setDescription("Test Payment")->setInvoiceNumber(uniqid());
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl("REDACTED")->setCancelUrl("REDACTED");
$payment = new Payment();
$payment->setIntent('sale')->setPayer($payer)->setRedirectUrls($redirectUrls)->setTransactions([$transactions]);
try{
$payment->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getCode(); // Prints the Error Code
echo "<br>";
echo $ex->getData(); // Prints the detailed error message
echo "<br>";
die($ex);
} catch (Exception $ex) {
die($ex);
}
echo ($payment->getApprovalLink());
?>
I'd be tempted to blame PayPal for this, as it is a 500, but it's my first use o the REST API so I assume I made a silly mistake. I've also attempted changing uniqid() to a static number, but that made no change. Should I submit a contact request to PayPal, and if so, how do I get the necessary information for that?

PHP Papal SDK - list of transactions

Just trying get list of all incoming transactions to our PayPal account with PayPal PHP SDK, but result from following example return me still just one record (and we have thousands of payments in our live environment). According PP documentation everything looks ok... Is there any different service for incoming payments?
<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
require __DIR__ . '/vendor/autoload.php';
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'...SUssUIJQ6zEOdQBI7nUG...', // ClientID
'...YHw3aCroq0mbqSdzimPq...' //Secret hash
)
);
$apiContext->setConfig(array('mode' => 'live'));
$payment = new \PayPal\Api\Payment();
try {
$params = array();
$payments = $payment->all($params, $apiContext);
echo $payments;
} catch (Exception $ex) {
print_r($ex);
}

DUPLICATE_REQUEST_ID while accepting payment from paypal using credit card

I am getting this error when I try to use my sandbox account on my local server to get credit card payments. I have no idea how to handle this any help will be appreciated. Here is the error I received:
int(400)
string(212) "{"name":"DUPLICATE_REQUEST_ID","message":"PayPal-Request-Id header was already used.","information_link":"https://developer.paypal.com/webapps/developer/docs/api/#DUPLICATE_REQUEST_ID","debug_id":"2845e6fe9b1b5"}"
exception 'PayPal\Exception\PayPalConnectionException' with message 'Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/payments/payment.' in D:\xampp\htdocs\paypal1\lib\PayPal\Core\PayPalHttpConnection.php:177
Stack trace:
#0 D:\xampp\htdocs\paypal1\lib\PayPal\Transport\PayPalRestCall.php(73): PayPal\Core\PayPalHttpConnection->execute('{"intent":"sale...')
#1 D:\xampp\htdocs\paypal1\lib\PayPal\Common\PayPalResourceModel.php(102): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/payments/pa...', 'POST', '{"intent":"sale...', NULL)
#2 D:\xampp\htdocs\paypal1\lib\PayPal\Api\Payment.php(579): PayPal\Common\PayPalResourceModel::executeCall('/v1/payments/pa...', 'POST', '{"intent":"sale...', NULL, Object(PayPal\Rest\ApiContext), NULL)
#3 D:\xampp\htdocs\paypal1\sample\index.php(66): PayPal\Api\Payment->create(Object(PayPal\Rest\ApiContext))
#4 {main}
Here is my index file:
<?php
require 'bootstrap.php';
use PayPal\Api\Amount;
use PayPal\Api\CreditCard;
use PayPal\Api\Details;
use PayPal\Api\FundingInstrument;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\Transaction;
$card = new CreditCard();
$card->setType("visa")
->setNumber("43111*******44663")
->setExpireMonth("09")
->setExpireYear("2021")
->setCvv2("012")
->setFirstName("My")
->setLastName("Name");
$fi = new FundingInstrument();
$fi->setCreditCard($card);
$payer = new Payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
$product = "rambo dfdf";
$price = 305;
$shipping = 2.00;
$total = $price + $shipping;
$item = new Item();
$item->setName($product)
->setCurrency('USD')
->setQuantity(1)
->setPrice($price);
$itemList = new ItemList();
$itemList->setItems([$item]);
$details = new Details();
$details->setShipping($shipping)
->setSubtotal($price);
$amount = new Amount();
$amount->setCurrency('USD')
->setTotal($total)
->setDetails($details);
$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($itemList)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
$payment = new Payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
$request = clone $payment;
try {
$payment->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo "<pre>";
var_dump($ex->getCode()); // Prints the Error Code
var_dump( $ex->getData()); // Prints the detailed error message
die($ex);
echo "</pre>";
} catch (Exception $ex) {
echo "<pre>";
die($ex);
echo "</pre>";
}
return $payment;
Here is my bootstrap.php file:
<?php
/*
* Sample bootstrap file.
*/
// Include the composer Autoloader
// The location of your project's vendor autoloader.
$composerAutoload = dirname(dirname(dirname(__DIR__))) . '/autoload.php';
if (!file_exists($composerAutoload)) {
//If the project is used as its own project, it would use rest-api-sdk-php composer autoloader.
$composerAutoload = dirname(__DIR__) . '/vendor/autoload.php';
if (!file_exists($composerAutoload)) {
echo "The 'vendor' folder is missing. You must run 'composer update' to resolve application dependencies.\nPlease see the README for more information.\n";
exit(1);
}
}
require $composerAutoload;
require __DIR__ . '/common.php';
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Rest\ApiContext;
// Suppress DateTime warnings, if not set already
date_default_timezone_set(#date_default_timezone_get());
// Adding Error Reporting for understanding errors properly
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 = '*******************************';
$clientSecret = '****************************';
/**
* All default curl options are stored in the array inside the PayPalHttpConfig class. To make changes to those settings
* for your specific environments, feel free to add them using the code shown below
* Uncomment below line to override any default curl options.
*/
//PayPalHttpConfig::$defaultCurlOptions[CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_2;
/** #var \Paypal\Rest\ApiContext $apiContext */
$apiContext = getApiContext($clientId, $clientSecret);
return $apiContext;
/**
* Helper method for getting an APIContext for all calls
* #param string $clientId Client ID
* #param string $clientSecret Client Secret
* #return PayPal\Rest\ApiContext
*/
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' => '../PayPal.log',
'log.LogLevel' => 'DEBUG', // PLEASE USE `INFO` LEVEL FOR LOGGING IN LIVE ENVIRONMENTS
'cache.enabled' => true,
// 'http.CURLOPT_CONNECTTIMEOUT' => 30
// 'http.headers.PayPal-Partner-Attribution-Id' => '123123123'
//'log.AdapterFactory' => '\PayPal\Log\DefaultLogFactory' // Factory class implementing \PayPal\Log\PayPalLogFactory
)
);
// 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;
}
Try resetting the request id by replacing
$payment->create($apiContext);
With
$apiContext->resetRequestId();
$payment->create($apiContext);

Display Google Admin SDK JSON Response in PHP

Thanks to Emily, I found the php client library already. I need to retrieve a users data. There is a function in the API that can do so :
Google_DirectoryService.php
/**
* retrieve user (users.get)
*
* #param string $userKey Email or immutable Id of the user
* #param array $optParams Optional parameters.
* #return Google_User
*/
public function get($userKey, $optParams = array()) {
$params = array('userKey' => $userKey);
$params = array_merge($params, $optParams);
$data = $this->__call('get', array($params));
if ($this->useObjects()) {
return new Google_User($data);
} else {
return $data;
}
}
index.php
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DirectoryService.php';
$client = new Google_Client();
$client->setApplicationName("IAA SIS");
$client->setClientId('xxx.apps.googleusercontent.com');
$client->setClientSecret('xxx');
$client->setRedirectUri('http://mypage.com/oauth2callback');
$client->setDeveloperKey('xxx');
$client->setScopes(array('https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$service = new Google_DirectoryService($client);
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$results = $service->users->get('$email', 'public', $optParams); //Pass email to function parameter ? I'm not sure.
?>
I think the way I pass the parameter is wrong which i got error after adding the last line. How do I pass users login email to the function correctly ?
The error i got is :
[08-Jan-2014 03:17:33 America/Chicago] PHP Fatal error: Uncaught exception 'Google_ServiceException' with message 'Error calling GET https://www.googleapis.com/admin/directory/v1/users/me?key=: (403) Insufficient Permission' in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php:66
Stack trace:
#0 /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php(36): Google_REST::decodeHttpResponse(Object(Google_HttpRequest))
#1 /home2/iaapro/public_html/php/google-api-php-client/src/service/Google_ServiceResource.php(186): Google_REST::execute(Object(Google_HttpRequest))
#2 /home2/iaapro/public_html/php/google-api-php-client/src/contrib/Google_DirectoryService.php(653): Google_ServiceResource->__call('get', Array)
#3 /home2/iaapro/public_html/php/google-plus-access.php(44): Google_UsersServiceResource->get('me')
#4 /home2/iaapro/public_html/php/index.php(2): include_once('/home2/iaapro/p...')
#5 {main}
thrown in /home2/iaapro/public_html/php/google-api-php-client/src/io/Google_REST.php on line 66
In addition, I have checked "Enable API Access" on admin.google.com and enable Admin SDK on Google APIs Console.
Can anyone gives me some help please ?
Finally, I figured out how to call the array using Google directory service API. Please refer to the code below:
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_PlusService.php';
require_once 'google-api-php-client/src/contrib/Google_Oauth2Service.php';
require_once 'google-api-php-client/src/contrib/Google_DirectoryService.php';
session_start();
$client = new Google_Client();
$client->setApplicationName("ApplicationName");
//*********** Replace with Your API Credentials **************
$client->setClientId('Your_Client_ID');
$client->setClientSecret('Your_Client_Sercret');
$client->setRedirectUri('http://example.com/oauth2callback');
$client->setDeveloperKey('Your_API_Key');
//************************************************************
$client->setScopes(array('https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/admin.directory.user.readonly'));
$plus = new Google_PlusService($client);
$oauth2 = new Google_Oauth2Service($client); // Call the OAuth2 class for get email address
$adminService = new Google_DirectoryService($client); // Call directory API
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
if (isset($_GET['code'])) {
$client->authenticate();
$_SESSION['access_token'] = $client->getAccessToken();
header('Location: http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']);
}
if (isset($_SESSION['access_token'])) {
$client->setAccessToken($_SESSION['access_token']);
}
if ($client->getAccessToken()) {
$user = $oauth2->userinfo->get();
$me = $plus->people->get('me');
$email = filter_var($user['email'], FILTER_SANITIZE_EMAIL); // get the USER EMAIL ADDRESS using OAuth2
$optParams = array('maxResults' => 100);
$activities = $plus->activities->listActivities('me', 'public', $optParams);
$users = $adminService->users->get($email);
$_SESSION['access_token'] = $client->getAccessToken();
} else {
$authUrl = $client->createAuthUrl();
}
?>
Have you checked out the Google API PHP client library? (https://code.google.com/p/google-api-php-client/)
Also, they have a github page: https://github.com/google/google-api-php-client
Once you downloaded the library from the site, you can see that the library has the Google_DirectoryService

Categories