Hey there, fellow developer! Ready to dive into the world of PayPal integration? Let's get your PHP application hooked up with PayPal's API using their nifty REST SDK. Buckle up, because we're about to make your app a whole lot more powerful!
Before we jump in, make sure you've got:
First things first, let's get that SDK installed:
composer require paypal/rest-api-sdk-php
Now, let's set up those API credentials. Head over to your PayPal Developer Dashboard and grab your Client ID and Secret. Then, in your PHP code:
require 'vendor/autoload.php'; use PayPal\Rest\ApiContext; use PayPal\Auth\OAuthTokenCredential; $apiContext = new ApiContext( new OAuthTokenCredential( 'YOUR_CLIENT_ID', 'YOUR_SECRET' ) );
Let's create a simple payment:
use PayPal\Api\Amount; use PayPal\Api\Payer; use PayPal\Api\Payment; use PayPal\Api\RedirectUrls; use PayPal\Api\Transaction; $payer = new Payer(); $payer->setPaymentMethod("paypal"); $amount = new Amount(); $amount->setCurrency("USD") ->setTotal(100); $transaction = new Transaction(); $transaction->setAmount($amount) ->setDescription("Amazing product"); $redirectUrls = new RedirectUrls(); $redirectUrls->setReturnUrl("http://example.com/success") ->setCancelUrl("http://example.com/cancel"); $payment = new Payment(); $payment->setIntent("sale") ->setPayer($payer) ->setRedirectUrls($redirectUrls) ->setTransactions(array($transaction)); try { $payment->create($apiContext); echo $payment; } catch (Exception $ex) { echo "Error: " . $ex->getMessage(); }
After the user approves the payment, you'll need to execute it:
$paymentId = $_GET['paymentId']; $payment = Payment::get($paymentId, $apiContext); $execution = new PaymentExecution(); $execution->setPayerId($_GET['PayerID']); try { $result = $payment->execute($execution, $apiContext); echo "Payment executed successfully"; } catch (Exception $ex) { echo "Error: " . $ex->getMessage(); }
Sometimes things don't work out. Here's how to refund a payment:
use PayPal\Api\Amount; use PayPal\Api\Refund; use PayPal\Api\Sale; $saleId = 'SALE_ID'; $sale = new Sale(); $sale->setId($saleId); $refund = new Refund(); $refund->setAmount(new Amount(['total' => '10.00', 'currency' => 'USD'])); try { $refundedSale = $sale->refund($refund, $apiContext); echo "Refund processed successfully"; } catch (Exception $ex) { echo "Error: " . $ex->getMessage(); }
Always expect the unexpected! Wrap your API calls in try-catch blocks and log any errors:
use Monolog\Logger; use Monolog\Handler\StreamHandler; $logger = new Logger('paypal'); $logger->pushHandler(new StreamHandler('path/to/your/paypal.log', Logger::WARNING)); try { // Your PayPal API call here } catch (\PayPal\Exception\PayPalConnectionException $ex) { $logger->error('PayPal API Error: ' . $ex->getData()); } catch (Exception $ex) { $logger->error('Unexpected error: ' . $ex->getMessage()); }
Before going live, make sure to test thoroughly using PayPal's Sandbox environment. Just change your API context:
$apiContext->setConfig(['mode' => 'sandbox']);
Remember, keep those API credentials safe! Never commit them to version control. Instead, use environment variables or a secure configuration file.
To keep things speedy, cache your API context:
$apiContext = new ApiContext( new OAuthTokenCredential( 'YOUR_CLIENT_ID', 'YOUR_SECRET' ) ); $apiContext->setConfig([ 'cache.enabled' => true, 'cache.FileName' => '/tmp/auth.cache' ]);
And there you have it! You're now equipped to integrate PayPal into your PHP application like a pro. Remember, the PayPal API is vast and powerful, so don't be afraid to explore more features as you need them.
Keep coding, keep learning, and most importantly, have fun building awesome stuff! If you need more info, the PayPal Developer Docs are your best friend. Happy integrating!