Mastering E-commerce Excellence: Unleash Seamless Laravel 2Checkout Integration Today!
Laravel 2Checkout Integration:
In the ever-evolving landscape of e-commerce, providing seamless payment experiences is paramount. Laravel, a robust PHP framework, makes this task easier with its flexibility and powerful features. In this article, we’ll explore the integration of 2Checkout, a popular payment gateway, into a Laravel application. By the end of this guide, you’ll have a comprehensive understanding of the integration process, complete with code snippets and best practices.
Mastering E-commerce Excellence: Laravel Braintree Integration Unleashed
1. Setting Up 2Checkout Account
Before diving into Laravel 2Checkout integration, ensure you have a 2Checkout account. Obtain your Seller ID and Secret Word from the 2Checkout Dashboard.
2. Laravel Project Setup
Create a new Laravel project using Composer:
composer create-project --prefer-dist laravel/laravel 2checkout-laravel
Navigate to the project folder:
cd 2checkout-laravel
3. Database Configuration
Configure your database details in the .env
file:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database
DB_USERNAME=your_username
DB_PASSWORD=your_password
Run migrations to create the necessary tables:
php artisan migrate
4. Creating the Model
Generate a model for your payments:
php artisan make:model Payment -m
In the generated migration file, modify the up
method to include the necessary fields:
public function up()
{
Schema::create('payments', function (Blueprint $table) {
$table->id();
$table->string('transaction_id');
$table->decimal('amount', 8, 2);
$table->string('status');
$table->timestamps();
});
}
Run the migration again:
php artisan migrate
5. Setting Up Routes
Define the necessary routes in the web.php
file:
use App\Http\Controllers\PaymentController;
Route::get('/payment', [PaymentController::class, 'showPaymentForm']);
Route::post('/payment/checkout', [PaymentController::class, 'checkout']);
Route::get('/payment/success', [PaymentController::class, 'paymentSuccess']);
Route::get('/payment/cancel', [PaymentController::class, 'paymentCancel']);
6. Building the Controller
Generate a controller:
php artisan make:controller PaymentController
In PaymentController.php
, implement the necessary methods:
use Illuminate\Http\Request;
use Omnipay\Omnipay;
class PaymentController extends Controller
{
public function showPaymentForm()
{
return view('payment');
}
public function checkout(Request $request)
{
$gateway = Omnipay::create('TwoCheckout');
$gateway->initialize([
'accountId' => env('2CHECKOUT_ACCOUNT_ID'),
'secretKey' => env('2CHECKOUT_SECRET_KEY'),
'testMode' => env('2CHECKOUT_TEST_MODE'),
]);
$response = $gateway->purchase([
'amount' => $request->input('amount'),
'currency' => 'USD',
'transactionId' => uniqid(),
'returnUrl' => url('/payment/success'),
'cancelUrl' => url('/payment/cancel'),
])->send();
if ($response->isRedirect()) {
$response->redirect();
} else {
// Handle error
}
}
public function paymentSuccess(Request $request)
{
// Get the payment gateway instance
$gateway = Omnipay::create('TwoCheckout');
$gateway->setAccountSid(config('services.2checkout.sid'));
$gateway->setSecretKey(config('services.2checkout.secret'));
// Capture the payment details from the callback
$response = $gateway->completePurchase(['token' => $request->input('token')])->send();
if ($response->isSuccessful()) {
// Payment was successful
$transactionReference = $response->getTransactionReference();
// Process your successful payment logic here
// For example, update the database with the transaction details
return view('payment.success', ['transactionReference' => $transactionReference]);
} else {
// Payment failed
$error = $response->getMessage();
// Log the error or handle it accordingly
Log::error("Payment failed: $error");
return view('payment.error', ['error' => $error]);
}
}
public function paymentCancel(Request $request)
{
// Get the payment gateway instance
$gateway = Omnipay::create('TwoCheckout');
$gateway->setAccountSid(config('services.2checkout.sid'));
$gateway->setSecretKey(config('services.2checkout.secret'));
// Capture the payment details from the callback
$response = $gateway->completePurchase(['token' => $request->input('token')])->send();
if ($response->isCancelled()) {
// Payment was cancelled by the user
// Perform any necessary actions, such as redirecting or displaying a message
return view('payment.cancel', ['message' => 'Payment has been canceled by the user.']);
} else {
// Unexpected response, log it (if necessary) and handle accordingly
$error = $response->getMessage();
Log::error("Unexpected response during payment cancellation: $error");
return view('payment.error', ['error' => $error]);
}
}
7. Creating Views for Payment
Create a Blade view file (payment.blade.php
) to display the payment form.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>2Checkout Payment</title>
</head>
<body>
<form action="/payment/checkout" method="post">
@csrf
<label for="amount">Amount:</label>
<input type="text" name="amount" required>
<button type="submit">Pay Now</button>
</form>
</body>
</html>
8. Testing the Integration
Run your Laravel development server:
php artisan serve
Visit http://localhost:8000/payment
in your browser, enter an amount, and proceed with the payment.
Recent Comments