Integrating PayPal payment gateway in Laravel without using packages requires a bit more manual work, but it's definitely doable. Here's a basic outline of the steps you'd need to follow:
Create a PayPal Business Account: If you haven't already, sign up for a PayPal business account at PayPal Developer.
Generate API Credentials: Once logged into your PayPal Developer account, navigate to the Dashboard and create a new REST API app. This will give you access to your Client ID and Secret, which you'll need to authenticate your requests.
Set up Routes: Define routes in your Laravel application to handle PayPal payment initiation and callback. For example, /payment to initiate payment and /payment/callback to handle PayPal's response.
Create Controller Methods: Implement controller methods for initiating the payment and handling the callback. In the payment initiation method, you'll craft a request to PayPal's API to create a payment. In the callback method, you'll verify the payment status and update your application's database accordingly.
Frontend Integration: Create frontend views to allow users to initiate payments. This could be a simple form where users enter payment details.
Make API Requests: Use Laravel's HTTP client or Guzzle to make requests to PayPal's REST API. You'll make requests to endpoints like /v1/payments/payment to create payments and /v1/payments/payment/{payment_id}/execute to execute payments.
Handle Callback: In the callback route handler, verify the payment status using the information PayPal sends back. Update your application's database accordingly.
Error Handling: Implement error handling throughout the process to handle cases where payments fail or there are errors in communication with PayPal.
Security: Ensure you're using HTTPS for all communication with PayPal to keep your transactions secure.
Testing: Test your integration thoroughly in PayPal's sandbox environment before deploying to production.
Here's a simplified example :
Step 1: Create a Laravel Project
laravel new paypal_integration
cd paypal_integration
Step 2: Set up Routes
Define routes in routes/web.php:
use App\Http\Controllers\PaymentController;
//paypal intgration
Route::post('/payment', [PaymentController::class, 'initiatePayment']);
Route::get('/payment/callback', [PaymentController::class, 'handleCallback']);
Step 3: Create a Controller
Generate a controller named PaymentController:
php artisan make:controller PaymentController
Full Code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class PaymentController extends Controller
{
public function initiatePayment(Request $request)
{
$clientId = '********************';
$clientSecret = '****************';
$credentials = base64_encode("$clientId:$clientSecret");
$accessToken = "Basic $credentials";
//dd($accessToken);
// Make request to PayPal API to create payment
$response = Http::withHeaders([
'Accept' => 'application/json',
'Authorization' => $accessToken,
//'Authorization' => 'Bearer YOUR_PAYPAL_ACCESS_TOKEN',
])->post('https://api.sandbox.paypal.com/v1/payments/payment', [
'intent' => 'sale',
'payer' => [
'payment_method' => 'paypal',
],
'transactions' => [
[
'amount' => [
'total' => '10.00',
'currency' => 'USD',
],
],
],
'redirect_urls' => [
'return_url' => url('/payment/callback'),
'cancel_url' => url('/'),
],
]);
// Handle response from PayPal API
$approvalUrl = collect($response->json('links'))->firstWhere('rel', 'approval_url')['href'];
// Redirect user to PayPal for payment approval
return redirect()->away($approvalUrl);
}
public function handleCallback(Request $request)
{
// Retrieve payment details from callback request
$paymentId = $request->input('paymentId');
$token = $request->input('token');
$payerId = $request->input('PayerID');
$clientId = '**************************';
$clientSecret = '***************************';
$credentials = base64_encode("$clientId:$clientSecret");
$accessToken = "Basic $credentials";
// Make request to PayPal API to execute payment
$response = Http::withHeaders([
'Accept' => 'application/json',
'Authorization' => $accessToken,
])->post("https://api.sandbox.paypal.com/v1/payments/payment/{$paymentId}/execute", [
'payer_id' => $payerId,
]);
// Check if payment was successful
if ($response->successful()) {
// Payment successful
// Retrieve payment details from the response if needed
$paymentDetails = $response->json();
dd($paymentDetails);
// Update your application's database with payment status
// Redirect user to appropriate page (success or failure)
return view('payment_confirmation');
} else {
dd('payment faid');
// Payment failed
// Handle the failure scenario
return redirect()->route('payment.failure');
}
dd($request->all());
// Verify PayPal callback
// Retrieve payment details from callback request
// Update your application's database with payment status
// Redirect user to appropriate page (success or failure)
return view('payment_confirmation');
}
}
Step 4: Create Views
Create a view named welcome.blade.php in resources/views/ folder for the payment initiation form:
<!DOCTYPE html>
<html>
<head>
<title>PayPal Integration</title>
</head>
<body>
<h1>Welcome to PayPal Integration</h1>
<form method="POST" action="{{ url('/payment') }}">
@csrf
<button type="submit">Make Payment</button>
</form>
</body>
</html>
Create another view named payment_confirmation.blade.php in the same folder for the payment confirmation page:
<!DOCTYPE html>
<html>
<head>
<title>Payment Confirmation</title>
</head>
<body>
<h1>Payment Successful</h1>
<p>Thank you for your payment!</p>
</body>
</html>
Step 5: Set up PayPal Developer Account
Create a PayPal Developer account at https://developer.paypal.com/.
Step 6: Generate API Credentials
Once logged in, create a new REST API app to get your Client ID and Secret.
Step 7: Replace Access Token
Replace YOUR_PAYPAL_ACCESS_TOKEN in PaymentController.php with the actual access token generated using your PayPal Client ID and Secret.
In this modified handleCallback() method:
We retrieve the payment details (paymentId, token, PayerID) from the callback request.
We then make a request to PayPal's API to execute the payment using the retrieved paymentId and PayerID.
We check if the execution of the payment was successful. If the request is successful (i.e., status code 200), we consider the payment successful. You might want to handle other HTTP status codes differently as needed.
If the payment is successful, you can retrieve payment details from the response, update your application's database with payment status, and redirect the user to the payment confirmation page.
If the payment fails, you can redirect the user to an appropriate failure page.
Remember to replace 'YOUR_PAYPAL_ACCESS_TOKEN' with the actual access token generated using your PayPal Client ID and Secret, as explained earlier. Also, ensure proper error handling and logging to deal with various scenarios effectively.
No comments: