Building a PayPal payment gateway API in Laravel 11 involves several steps, including setting up a PayPal developer account, creating a new Laravel project, and integrating the PayPal API. Below is a step-by-step guide to help you through the process.
Step 1: Set Up Your PayPal Developer Account
- Create a PayPal Developer Account:
- Go to the PayPal Developer site and log in or create a new account.
- Create a New App:
- Navigate to the “Dashboard” and create a new app under “My Apps & Credentials.”
- Once created, you’ll get your Client ID and Secret, which will be used for authentication.
Step 2: Create a New Laravel Project
- Install Laravel:
bash
Copy code
composer create-project laravel/laravel paypal-integration
cd paypal-integration
- Set Up Your Environment:
- Open the
.env
file and configure your database and other settings.
Step 3: Install PayPal SDK
To interact with the PayPal API, you can use the official PayPal PHP SDK. Install it via Composer:
bash
Copy code
composer require paypal/rest-api-sdk-php
Step 4: Configure PayPal SDK
- Create a Configuration File:
- Create a new config file for PayPal. Run the command:
bash
Copy code
php artisan make:config paypal.php
- Add PayPal Configuration: In
config/paypal.php
, add the following:
php
Copy code
return [
'client_id' => env('PAYPAL_CLIENT_ID'),
'secret' => env('PAYPAL_SECRET'),
'mode' => env('PAYPAL_MODE', 'sandbox'), // or 'live'
];
- Update .env File: Add your PayPal credentials in your
.env
file:
dotenv
Copy code
PAYPAL_CLIENT_ID=your_client_id
PAYPAL_SECRET=your_secret
PAYPAL_MODE=sandbox // Change to 'live' for production
Step 5: Create Payment Controller
- Generate a Controller:
bash
Copy code
php artisan make:controller PaymentController
- Implement Payment Logic: Open
app/Http/Controllers/PaymentController.php
and add the following code:
php
Copy code
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Api\Amount;
use PayPal\Api\Payer;
use PayPal\Api\Item;
class PaymentController extends Controller
{
public function createPayment(Request $request)
{
$payer = new Payer();
$payer->setPaymentMethod('paypal');
$amount = new Amount();
$amount->setTotal($request->input('amount'));
$amount->setCurrency('USD');
$transaction = new Transaction();
$transaction->setAmount($amount)
->setDescription('Payment Description');
$redirectUrls = new RedirectUrls();
$redirectUrls->setReturnUrl(url('/payment/success'))
->setCancelUrl(url('/payment/cancel'));
$payment = new Payment();
$payment->setIntent('sale')
->setPayer($payer)
->setRedirectUrls($redirectUrls)
->setTransactions([$transaction]);
try {
$payment->create($this->getApiContext());
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
// Handle error
return response()->json(['error' => $ex->getMessage()]);
}
return response()->json(['paymentUrl' => $payment->getApprovalLink()]);
}
public function executePayment(Request $request)
{
$paymentId = $request->input('paymentId');
$payerId = $request->input('PayerID');
$payment = Payment::get($paymentId, $this->getApiContext());
$execution = new PaymentExecution();
$execution->setPayerId($payerId);
try {
$result = $payment->execute($execution, $this->getApiContext());
return response()->json(['message' => 'Payment successful!', 'result' => $result]);
} catch (\PayPal\Exception\PayPalConnectionException $ex) {
return response()->json(['error' => $ex->getMessage()]);
}
}
private function getApiContext()
{
$apiContext = new \PayPal\Rest\ApiContext(
new \PayPal\Auth\OAuthTokenCredential(
config('paypal.client_id'),
config('paypal.secret')
)
);
$apiContext->setConfig([
'mode' => config('paypal.mode'),
]);
return $apiContext;
}
}
Step 6: Define Routes
Open routes/web.php
and define routes for your payment endpoints:
php
Copy code
use App\Http\Controllers\PaymentController;
Route::post('/payment/create', [PaymentController::class, 'createPayment']);
Route::get('/payment/success', [PaymentController::class, 'executePayment']);
Route::get('/payment/cancel', function () {
return 'Payment was canceled.';
});
Step 7: Testing the Payment Flow
- Start the Laravel Server:
bash
Copy code
php artisan serve
- Test the Payment: Use a tool like Postman to send a POST request to
/payment/create
with a JSON body containing theamount
, and follow the response link to PayPal for payment processing.
Final Thoughts
Integrating PayPal into a Laravel 11 application is straightforward with the official SDK. By following the steps outlined above, you can set up a basic payment gateway. For production environments, ensure to handle security, error logging, and validation effectively. As you build more complex features, consider implementing webhooks for payment notifications and recurring payments.
For more information Visit These Links [Link1] [Link2] [Link3] [Link4] [Link5]