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) {
}
}
}
Related
I try to use the Paypal PHP SDK with laravel.
Everything works fine in Sandbox mode.
But when i go live i have a problem of config loading when the request come back after paiement on paypal platform.
My problem is on this file /lib/PayPal/Handler/RestHandler.php, $config is empty
private function _getEndpoint($config)
{
if (isset($config['service.EndPoint'])) {
return $config['service.EndPoint'];
} elseif (isset($config['mode'])) {
switch (strtoupper($config['mode'])) {
case 'SANDBOX':
return PayPalConstants::REST_SANDBOX_ENDPOINT;
break;
case 'LIVE':
return PayPalConstants::REST_LIVE_ENDPOINT;
break;
default:
throw new PayPalConfigurationException('The mode config parameter must be set to either sandbox/live');
break;
}
} else {
// Defaulting to Sandbox
return PayPalConstants::REST_SANDBOX_ENDPOINT;
}
}
My problem is that the config is not loaded here.
I did this in my laravel app : Add a config file paypal.php
<?php
return [
'settings' => array(
'mode' => env('PAYPAL_MODE','LIVE'),
'service.EndPoint' => env('PAYPAL_ENDPOINT','https://api.paypal.com/'),
'http.ConnectionTimeOut' => 30,
'log.LogEnabled' => true,
'log.FileName' => storage_path() . '/logs/paypal.log',
'log.LogLevel' => 'ERROR'
),
];
I handle my ApiContext like this in a PayPalController
public static function generatePaypalApiContext(Connexion $connexion)
{
if (isset($connexion->data["paypal_client_id"]) && isset($connexion->data["paypal_client_secret"])) {
$apiContext = new ApiContext(new OAuthTokenCredential($connexion->data["paypal_client_id"], $connexion->data["paypal_client_secret"]));
$paypal_conf = config('paypal');
$apiContext->setConfig($paypal_conf['settings']);
Session::put('paypal_api_context', $apiContext);
} else {
return false;
}
return $apiContext;
}
and this is my function to execute the paiement
public static function getPaymentStatus(string $payerId)
{
/** Get the payment ID before session clear **/
$payment_id = Session::get('paypal_payment_id');
/** clear the session payment ID **/
Session::forget('paypal_payment_id');
$apiContext = Session::get('paypal_api_context');
$payment = Payment::get($payment_id, $apiContext);
$execution = new PaymentExecution();
$execution->setPayerId($payerId);
/**Execute the payment **/
$result = $payment->execute($execution, $apiContext);
if ($result->getState() == 'approved') {
return true;
}
return false;
}
What's wrong ?
Thanks
Is this a new integration? If so, the v1 PayPal-PHP-SDK is old and deprecated and should not be used for anything.
Instead, use the v2 Checkout-PHP-SDK
I found a way. Passing the Api context to my PayPalController::construct() and stop to use functions in static.
I am using PayPal rest api payment gateway method for payment, when I was using demo details this is working fine but when I used the live details it is returning error, Like
'We aren't able to process your payment using your PayPal account at this time. Please go back to the merchant and try using a different payment method.'
some time I also got the message of invalid details,
{"error":"invalid_client","error_description":"Client Authentication failed"}
I am using 'REST API SDK for PHP' got from the GitHub.
I have updated all the necessary information in the developer PayPal for live mode, but still getting issue.
This is my code what I tried
require __DIR__ . '/vendor/autoload.php';
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
// ClientID
// ClientSecret
)
);
$apiContext->setConfig(
array(
'log.LogEnabled' => true,
'log.FileName' => 'PayPal.log',
'log.LogLevel' => 'FINE',
'mode' => 'live',
)
);
$payer = new \PayPal\Api\Payer();
$payer->setPaymentMethod('paypal');
$amount = new \PayPal\Api\Amount();
$amount->setTotal($_SESSION['partner_payment'][1]);
$amount->setCurrency('USD');
$transaction = new \PayPal\Api\Transaction();
$transaction->setAmount($amount);
$redirectUrls = new \PayPal\Api\RedirectUrls();
$redirectUrls->setReturnUrl("https://mydomain/paypal/success.php")
->setCancelUrl("https://mydomain/paypal/cancel.php");
$payment = new \PayPal\Api\Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setTransactions(array($transaction))
->setRedirectUrls($redirectUrls);
try {
$payment->create($apiContext);
//echo $payment;
//echo "\n\nRedirect user to approval_url: " . $payment-
>getApprovalLink() . "\n";
header("Location:".$payment->getApprovalLink());
}
catch (\PayPal\Exception\PayPalConnectionException $ex) {
echo $ex->getData();
}
----Output:----
We aren't able to process your payment using your PayPal account at this time. Please go back to the merchant and try using a different payment method.
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();
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) {
}
To upload files to Google Drive using service account, I have written the following code which is from this link: https://developers.google.com/drive/web/service-accounts
My code:
require_once "google-api-php-client/src/Google_Client.php";
require_once "google-api-php-client/src/contrib/Google_DriveService.php";
require_once "google-api-php-client/src/contrib/Google_Oauth2Service.php";
session_start();
$DRIVE_SCOPE = 'https://www.googleapis.com/auth/drive';
$SERVICE_ACCOUNT_EMAIL = '<some-id>#developer.gserviceaccount.com';
$SERVICE_ACCOUNT_PKCS12_FILE_PATH = '/path/to/<public_key_fingerprint>-privatekey.p12';
/**
* Build and returns a Drive service object authorized with the service accounts.
*
* #return Google_DriveService service object.
*/
function buildService() {
$key = file_get_contents($SERVICE_ACCOUNT_PKCS12_FILE_PATH);
$auth = new Google_AssertionCredentials(
SERVICE_ACCOUNT_EMAIL,
array(DRIVE_SCOPE),
$key);
$client = new Google_Client();
$client->setUseObjects(true);
$client->setAssertionCredentials($auth);
return new Google_DriveService($client);
}
function uploadFile($service, $mime, $src) {
//Insert a file
$file = new Google_DriveFile();
$file->setMimeType($mime);
$data = file_get_contents($src);
try {
//ERROR HERE: cannot insert (upload) file
$createdFile = $service->files->insert($file,
array(
'data' => $data,
'mimeType' => $mime,
'convert' => true,
)
);
return $createdFile;
} catch (Exception $e) {
print "An error occurred: " . $e->getMessage();
}
}
$service = buildService();
When I call the buildService() method, it gives me an error:
Catchable fatal error: Object of class Google_AssertionCredentials could not be converted to string in /opt/lampp/htdocs/ajaxGoogleDrive/google-api-php-client/src/auth/Google_OAuth2.php on line 197
Where am I going wrong?