Save credit card into Paypal - php

I am trying to save credit card into paypal using paypal php sdk using the bellow code.
<?php
require 'PayPal-PHP-SDK-master/vendor/autoload.php';
$clientId = 'XXXXXXXXXX';
$clientSecret = 'XXXXXXXXX';
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\CreditCard;
use PayPal\Rest\ApiContext;
$sdkConfig = array(
"mode" => "sandbox"
);
$apiContext = $apiContext = new ApiContext(new OAuthTokenCredential(
$clientId,
$clientSecret
));
$creditcard = new CreditCard();
$creditcard->setId(101);
$creditcard->setNumber('4111111111111111');
$creditcard->setType('visa');
$creditcard->setExpireMonth(12);
$creditcard->setExpireYear(2020);
$creditcard->setCvv2(123);
$request = clone $creditcard;
try {
$output = $creditcard->create($apiContext);
echo "success";
} catch (Exception $ex) {
echo $ex;
exit(1);
}
But it is not working and i got exception like bellow
exception 'PayPal\Exception\PayPalConnectionException' with message
'Got Http response code 400 when accessing
https://api.sandbox.paypal.com/v1/vault/credit-cards.' in
/var/www/html/test/paypalcard/PayPal-PHP-SDK-master/lib/PayPal/Core/PayPalHttpConnection.php:202
Stack trace: #0
/var/www/html/test/paypalcard/PayPal-PHP-SDK-master/lib/PayPal/Transport/PayPalRestCall.php(78):
PayPal\Core\PayPalHttpConnection->execute('{"id":101,"numb...') #1
/var/www/html/test/paypalcard/PayPal-PHP-SDK-master/lib/PayPal/Common/PayPalResourceModel.php(104):
PayPal\Transport\PayPalRestCall->execute(Array, '/v1/vault/credi...',
'POST', '{"id":101,"numb...', NULL) #2
/var/www/html/test/paypalcard/PayPal-PHP-SDK-master/lib/PayPal/Api/CreditCard.php(443):
PayPal\Common\PayPalResourceModel::executeCall('/v1/vault/credi...',
'POST', '{"id":101,"numb...', NULL, Object(PayPal\Rest\ApiContext),
NULL) #3 /var/www/html/test/paypalcard/cardtest.php(32):
PayPal\Api\CreditCard->create(Object(PayPal\Rest\ApiContext)) #4
{main}
What is wrong with my code and what changes need to add for this?

Related

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?

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

Creating an Invoice with Paypal-Php-SDK fails with "Can not deserialize instance of java..." error

I'm trying to create an invoice with Paypal-Php-Sdk, everything's okay, but when I try to set Billing Info something goes wrong and I get this error:
{"name":"VALIDATION_ERROR","message":"Invalid request - see details.","debug_id":"2d34973f0cfef","details":[{"field":"billing_info","issue":"Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at line:1, column:2"}]}exception 'PayPal\Exception\PayPalConnectionException' with message 'Got Http response code 400 when accessing https://api.sandbox.paypal.com/v1/invoicing/invoices.' in /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Core/PayPalHttpConnection.php:176
Stack trace:
#0 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Transport/PayPalRestCall.php(74): PayPal\Core\PayPalHttpConnection->execute('{"billing_info"...')
#1 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Common/PayPalResourceModel.php(103): PayPal\Transport\PayPalRestCall->execute(Array, '/v1/invoicing/i...', 'POST', '{"billing_info"...', NULL)
#2 /var/www/admin/data/www/****/vendor/paypal/rest-api-sdk-php/lib/PayPal/Api/Invoice.php(736): PayPal\Common\PayPalResourceModel::executeCall('/v1/invoicing/i...', 'POST', '{"billing_info"...', NULL, Object(PayPal\Rest\ApiContext), NULL)
#3 var/www/admin/data/www/****/application/controllers/store.php(487): PayPal\Api\Invoice->create(Object(PayPal\Rest\ApiContext))
#4 [internal function]: Store->payment()
#5 /var/www/admin/data/www/****/system/core/CodeIgniter.php(359): call_user_func_array(Array, Array)
#6 /var/www/admin/data/www/****/index.php(202): require_once('/var/www/admin/...')
#7 {main}
Here's the code I use:
$client_id = "****";
$secret = "****";
$apiContext = new ApiContext(new OAuthTokenCredential(
$client_id, $secret));
$merchantInfo = new PayPal\Api\MerchantInfo();
$merchantInfo->setEmail("****");
$merchantInfo->setWebsite("****");
$billingInfo = new PayPal\Api\BillingInfo();
$billingInfo->setEmail("****");
$invoice = new PayPal\Api\Invoice();
$invoice->setMerchantInfo($merchantInfo);
$invoice->setBillingInfo($billingInfo);
try
{
$invoice->create($apiContext);
} catch (PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getData();
die($ex);
} catch (Exception $ex) {
die($ex);
}
Here's what I've received from Paypal support:
Change these two lines to this:
$invoice->setMerchantInfo(array($merchantInfo));
$invoice->setBillingInfo(array($billingInfo));
Both billing info and merchant info takes in array of objects, not an object directly.
It's strange but it started to work when I changed this only for Billing Info, so the right code for me was:
$invoice->setMerchantInfo($merchantInfo);
$invoice->setBillingInfo(array($billingInfo));

Insufficient Permission in Mirror API Insert Account using PHP

I have PHP code that Google PHP Mirror API to insert user account.
if(isset($_GET['userToken'])){
$userToken=$_GET['userToken'];
$key = file_get_contents($key_file_location);
$cred = new Google_Auth_AssertionCredentials(
'service-email-here',
array('https://www.googleapis.com/auth/glass', 'https://www.googleapis.com/auth/glass.thirdpartyauth'),
$key
);
$client->setAssertionCredentials($cred);
$mirrorService = new Google_Service_Mirror($client);
$_SESSION['access_token'] = $client->getAccessToken();
insert_account($mirrorService, $userToken, $email, $api_email);
exit();
}
function insert_account($service,$userToken, $email, $api_email)
{
$accountType='package-name-here';
$accountName='service-email-here';
$authtoken=null;
$postBody = new Google_Service_Mirror_Account();
$postBody->setAuthTokens($authtoken);
$userdata=array("email"=>$email);
$postBody->setUserData($userdata);
try {
$account = $service->accounts->insert($userToken, $accountType, $accountName, $postBody);
return $account;
} catch (Exception $e) {
echo "exception: ".$e;
return null;
}
}
I get an error which says:
exception: exception 'Google_Service_Exception' with message 'Error calling POST https://www.googleapis.com/mirror/v1/accounts/usertokenhere/package-name-here/service-email-here: (403) Insufficient Permission' in app-path/Google/Http/REST.php:79
Stack trace:
#0 app-path/Google/Http/REST.php(44): Google_Http_REST::decodeHttpResponse(Object(Google_Http_Request))
#1 app-path/Google/Client.php(508): Google_Http_REST::execute(Object(Google_Client), Object(Google_Http_Request))
#2 app-path/Google/Service/Resource.php(195): Google_Client->execute(Object(Google_Http_Request))
#3 app-path/Google/Service/Mirror.php(409): Google_Service_Resource->call('insert', Array, 'Google_Service_...')
#4 app-path/util.php(52): Google_Service_Mirror_Accounts_Resource->insert('8ce7d2ffbe6f693...', 'com.tenpearls.l...', '568533774877-an...', Object(Google_Service_Mirror_Account))
#5 app-path/add-your-own-camera.php(59): insert_account(Object(Google_Service_Mirror), '8ce7d2ffbe6f693...', 'safdar.tp#gmail...', '568533774877-an...')
#6 {main}
Why am I getting the insufficient permission error? I added the scope https://www.googleapis.com/auth/glass.thirdpartyauth which is required to add accounts using mirror api.
I need to insert user account using mirror API.
You do not need the scope https://www.googleapis.com/auth/glass. In fact, this is not a valid scope at all.
The only scope you need for adding an account on the device using a service account is https://www.googleapis.com/auth/glass.thirdpartyauth.
Calling insert account method required separate service client object. Code can be viewed here: http://goo.gl/DVggO6

Uncaught PPConnectionException Http response code 400

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!...

Categories