PayPal PHP SDK API - Get all Transactions - php

I want to use PayPal PHP SDK API to list all my Payments/Transactions. For Sandbox Credentials I`m finally successfully, but if i switch to LIVE Credentials the Result is just:
{
"count": 0
}
...Yes im switching to LIVE with:
$apiContext->setConfig(array('mode' => 'live'));
What could be my failure? Here is my Full Code:
<?php
// 1. Autoload the SDK Package. This will include all the files and classes to your autoloader
require __DIR__ . '/autoload.php';
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'ABC', // ClientID
'DEF' // ClientSecret
)
);
$apiContext->setConfig(array('mode' => 'live'));
#$apiContext = new \PayPal\Rest\ApiContext(
# new \PayPal\Auth\OAuthTokenCredential(
# 'XYZ', // ClientID
# 'XYZZ' // ClientSecret
# )
#);
// Test
//require 'CreatePayment.php';
//use PayPal\Api\Payment;
$payment = new \PayPal\Api\Payment();
try {
$params = array('count' => 10, 'start_index' => 0);
$payments = $payment->all($params, $apiContext);
echo $payments;
} catch (Exception $ex) {
}

Related

linking google calendar API with laravel to create calendars and events

I am trying to use Google's calendar API to create calendars and save them into my google calendar directly through my app, I would also like to create events but I cant seem to get this to work, there's no error whatsoever but still I don't see the calendar in my list.
$client = new \Google_Client();
$client->setApplicationName("GOOGLE CALENDAR");
$client->addScope(\Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('pr-test-4ad4a00e3031.json');
$client->setAccessType("offline");
$service = new \Google_Service_Calendar($client);
$calenders = new \Google_Service_Calendar_Calendar();
$calenders->setDescription('ramzi');
$calenders->setSummary('test');
$service->calendars->insert($calenders);
print_r($calenders);
the JSON file has the credentials.
And this is the output I get when I print the variable $calenders
Google_Service_Calendar_Calendar Object
(
[conferencePropertiesType:protected] => Google_Service_Calendar_ConferenceProperties
[conferencePropertiesDataType:protected] =>
[description] => ramzi
[etag] =>
[id] =>
[kind] =>
[location] =>
[summary] => test
[timeZone] =>
[internal_gapi_mappings:protected] => Array
(
)
[modelData:protected] => Array
(
)
[processed:protected] => Array
(
)
)
This code will help you to achieve what you are trying to do(Create new calendars and events in them):
<?php
require __DIR__ . '/vendor/autoload.php';
function getClient(){
$client = new Google_Client();
$client->setApplicationName('Calendar API PHP');
$client->addScope(Google_Service_Calendar::CALENDAR);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');
$client->setPrompt('select_account consent');
// Load previously authorized token from a file, if it exists.
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
$tokenPath = 'token.json';
if (file_exists($tokenPath)) {
$accessToken = json_decode(file_get_contents($tokenPath), true);
$client->setAccessToken($accessToken);
}
// If there is no previous token or it's expired.
if ($client->isAccessTokenExpired()) {
// Refresh the token if possible, else fetch a new one.
if ($client->getRefreshToken()) {
$client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
} else {
// Request authorization from the user.
$authUrl = $client->createAuthUrl();
printf("Open the following link in your browser:\n%s\n", $authUrl);
print 'Enter verification code: ';
$authCode = trim(fgets(STDIN));
// Exchange authorization code for an access token.
$accessToken = $client->fetchAccessTokenWithAuthCode($authCode);
$client->setAccessToken($accessToken);
// Check to see if there was an error.
if (array_key_exists('error', $accessToken)) {
throw new Exception(join(', ', $accessToken));
}
}
// Save the token to a file.
if (!file_exists(dirname($tokenPath))) {
mkdir(dirname($tokenPath), 0700, true);
}
file_put_contents($tokenPath, json_encode($client->getAccessToken()));
}
return $client;
}
function createCalendar($service){
$calendar = new Google_Service_Calendar_Calendar();
$calendar->setSummary('calendarSummary');
$calendar->setTimeZone('America/Los_Angeles');
try {
$createdCalendar = $service->calendars->insert($calendar);
echo $createdCalendar->getId();
return $createdCalendar->getId();
} catch(Exception $e) {
printf('An error occured creating the Calendar ' . $e->getMessage());
return null;
}
}
function insertMyevents($service, $calendarId){
$event = new Google_Service_Calendar_Event(array(
'summary' => 'Google I/O 2019',
'location' => '800 Howard St., San Francisco, CA 94103',
'description' => 'A chance to hear more about Google\'s developer products.',
'start' => array(
'dateTime' => '2019-11-13T09:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
),
'end' => array(
'dateTime' => '2019-11-14T17:00:00-07:00',
'timeZone' => 'America/Los_Angeles',
)
));
try{
$event = $service->events->insert($calendarId, $event);
} catch(Exception $e) {
printf('An error occured inserting the Events ' . $e->getMessage());
}
}
if (php_sapi_name() != 'cli') {
throw new Exception('This application must be run on the command line.');
}
/**
* Returns an authorized API client.
* #return Google_Client the authorized client object
*/
// Get the API client and construct the service object.
$client = getClient();
$service = new Google_Service_Calendar($client);
// Creeate new calendar
$calendarId = createCalendar($service);
// Insert events into new Calendar if it was created succesfully
if($calendarId){
insertMyevents($service, $calendarId);
}
You were creating the $client in the wrong way without setting all the previous steps as it is said in the Quickstart. I also recommend you to check the next links, which bring some examples on how to use the Calendar API for PHP and the docs from all the methods you could use:
Calendars: insert
Events: insert
Calendar API - PHP

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

Has anyone implemented the PayPal PHP SDK with an openssl certificate?

I read the documentation about security and concerns, but I can see any example with how use a .pem file to autenticate to PayPal API V2, the classic version has this feature. I want to send payments but using this method.
Has anyone share some code to see?
this is my code
require __DIR__ . '/PayPal-PHP-SDK/autoload.php';
class PaymentPayPal
{
public static function SendPayment($member)
{
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'ClientID','ClientSecret'
)
);
$apiContext->setConfig(
array(
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
)
);
$payouts = new \PayPal\Api\Payout();
$senderBatchHeader = new \PayPal\Api\PayoutSenderBatchHeader();
$senderBatchHeader->setSenderBatchId(uniqid())
->setEmailSubject("You have a payment");
$payouts->setSenderBatchHeader($senderBatchHeader);
$senderItem1 = new \PayPal\Api\PayoutItem();
$senderItem1->setRecipientType('Email')
->setNote('Thanks you.')
->setReceiver($member['email'])
->setSenderItemId(uniqid())
->setAmount(new \PayPal\Api\Currency('{
"value":"'.$member['amount'].'",
"currency":"USD"
}'));
$payouts->addItem($senderItem1);
try {
$output = $payouts->create(null, $apiContext);
var_dump($output);
$status = \PayPal\Api\Payout::get($output->batch_header->payout_batch_id, $apiContext);
var_dump($status);
} catch (Exception $ex) {
}
}
}

Paypal/Laravel can't make a Live payment

I've followed this tutorial to implement payment using Paypal services on my website: https://www.youtube.com/watch?v=q5Xb5r4MUB8
But when i want to flip from SandBox mode to Live mode (which is the real payment) all my transactions goes to the SandBox history (you can check it in your Paypal account).
Here is the code of the function "store()" that do the payment:
public function store(Request $request)
{
// ### CreditCard
$card = Paypalpayment::creditCard();
$card->setType("visa")
->setNumber("Some_Numbers")
->setExpireMonth("05")
->setExpireYear("2017")
->setCvv2("smth")
->setFirstName("MyName")
->setLastName("MyLastName");
$fi = Paypalpayment::fundingInstrument();
$fi->setCreditCard($card);
$payer = Paypalpayment::payer();
$payer->setPaymentMethod("credit_card")
->setFundingInstruments(array($fi));
//Payment Amount
$amount = Paypalpayment::amount();
$amount->setCurrency("EUR")
->setTotal("3");
$transaction = Paypalpayment::transaction();
$transaction->setAmount($amount)
->setDescription("Payment description")
->setInvoiceNumber(uniqid());
// ### Payment
// A Payment Resource; create one using
// the above types and intent as 'sale'
$payment = Paypalpayment::payment();
$payment->setIntent("sale")
->setPayer($payer)
->setTransactions(array($transaction));
try {
$payment->create($this->_apiContext);
} catch (\PPConnectionException $ex) {
return "Exception: " . $ex->getMessage() . PHP_EOL;
exit(1);
}
dd($payment);
}
Look what $this->_apiContext contains. There is a mode that needs to be set to live to make it work.
If not found, you can create apiContext object as shown here:
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
'Live ClientId', // ClientID
'Live Client Secret' // ClientSecret
)
);
$apiContext->setConfig(
array(
'mode' => 'live',
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE'
)
);
and use $apiContext instead when you call $payment->create();

Categories