Effortlessly integrate Google Pay with Laravel
Are you an e-commerce business owner looking to enhance your payment options for your customers? Integrating Google Pay with your Laravel website can provide your users with a hassle-free and secure payment experience. In this step-by-step guide, we will show you how to integrate Google Pay with Laravel with code examples.
RESTful APIs with JWT Authentication in Laravel
Benefit of using google pay with laravel
Google Pay is a digital wallet platform that allows users to make online and in-store payments using their Android devices. When used in conjunction with Laravel, a PHP web application framework, GPay can offer several benefits, including:
- Seamless Integration: Google Pay offers a well-documented API that makes integration with Laravel easy and straightforward. This means that developers can quickly set up payment processing functionality within their Laravel applications.
- Secure Payments: Google Pay provides an additional layer of security for transactions made through the platform. Transactions made through GPay are authenticated with a unique token and encrypted, which helps protect sensitive customer information.
- Improved User Experience: Google Pay offers a quick and easy checkout process, reducing the time it takes for users to complete a transaction. This can lead to improved conversion rates and increased customer satisfaction.
- Flexibility: Google Pay allows developers to accept payments from a variety of sources, including credit and debit cards, bank accounts, and gift cards. This flexibility can be useful for Laravel developers who want to offer their customers a range of payment options.
- Analytics and Reporting: GPay provides detailed analytics and reporting tools that allow developers to track payments, view transaction history, and generate reports. This information can be used to optimize payment processing and improve business operations.
Overall, using GPay with Laravel can provide a number of benefits, including seamless integration, secure payments, improved user experience, flexibility, and analytics. This can help developers build robust, user-friendly payment processing functionality within their Laravel applications.
There are two ways one is using package which is now not available and other one is using API and JS which I describe in the bottom of this article
Step 1: Set up Google Pay API
First, you need to set up the GPay API. Visit the GPay API page and follow the instructions provided to create a GPay API account. Once you’ve set up your account, you’ll need to create a new project and enable the GPay API.
Step 2: Install Laravel Google Pay Package
Next, you need to install the Laravel GPay package. You can do this by adding the package to your composer.json file and running the composer update command. The Laravel GPay package simplifies the process of integrating GPay with your Laravel application.
Step 3: Set up Configuration
After installing the package, you need to set up the configuration for the Laravel Google Pay package. To do this, add the following code to your .env file:
GOOGLE_PAY_ENVIRONMENT="TEST" # Environment can be either TEST or PRODUCTION
GOOGLE_PAY_MERCHANT_NAME="Your Merchant Name" # Replace this with your merchant name
GOOGLE_PAY_MERCHANT_ID="Your Merchant ID" # Replace this with your merchant ID
GOOGLE_PAY_MERCHANT_SECRET="Your Merchant Secret" # Replace this with your merchant secret
Step 4: Create a Payment Gateway
Next, you need to create a payment gateway for GPay. You can do this by creating a new payment gateway class in your Laravel application. Here’s an example code:
<?php
namespace App\PaymentGateways;
use Laravel\Cashier\Cashier;
use Illuminate\Support\Facades\Http;
use Google\ApiCore\ApiException;
use Google\Apis\PaymentsResellerSubscription\V1\SubscriptionPurchase;
use Google\Apis\PaymentsResellerSubscription\V1\SubscriptionsService;
class GooglePayGateway {
public function purchase($user, $product) {
$price = $product->price * 100; // Google Pay requires the price in cents
$environment = config('google-pay.environment');
$merchantId = config('google-pay.merchant_id');
$merchantSecret = config('google-pay.merchant_secret');
$merchantName = config('google-pay.merchant_name');
$paymentToken = $user->paymentMethods()->where('type', 'google_pay')->first()->payment_token;
$subscriptionsService = new SubscriptionsService();
$subscriptionsService->setAccessToken($paymentToken);
$subscriptionPurchase = new SubscriptionPurchase();
$subscriptionPurchase->setSku($product->id);
$subscriptionPurchase->setStartDate(date('Y-m-d\TH:i:s\Z'));
$subscriptionPurchase->setPlanQuantity(1);
try {
$subscriptionsService->subscriptions->purchase($merchantId, $subscriptionPurchase, ['merchantName' => $merchantName]);
} catch (ApiException $e) {
throw new Exception($e->getMessage());
}
}
}
Step 5: Enable Google Pay Button
Finally, you need to enable the GPay button on your Laravel application. You can do this by adding the following code to your checkout page:
<div id="google-pay-button"></div>
<script src="https://pay.google.com/gp/p/js/pay.js"></script>
After adding the code to your checkout page, you need to initialize the GPay button. Here’s an example code:
const paymentsClient = new google.payments.api.PaymentsClient({
environment: '{{ config('google-pay.environment') }}'
});
const paymentDataRequest = {
allowedPaymentMethods: ['CARD', 'TOKENIZED_CARD'],
transactionInfo: {
currencyCode: 'USD',
totalPriceStatus: 'FINAL',
totalPrice: '{{ $total }}'
},
merchantInfo: {
merchantId: '{{ config('google-pay.merchant_id') }}',
merchantName: '{{ config('google-pay.merchant_name') }}'
}
};
const googlePayButton = paymentsClient.createButton({
onClick: () => {
paymentsClient.loadPaymentData(paymentDataRequest)
.then(paymentData => {
const token = paymentData.paymentMethodData.tokenizationData.token;
// Save the payment token to your database
})
.catch(err => {
console.error(err);
});
}
});
document.getElementById('google-pay-button').appendChild(googlePayButton);
That’s it! You’ve successfully integrated GPay with Laravel. Your users can now pay using GPay on your e-commerce platform, providing them with a hassle-free and secure payment experience.
Second Method
To integrate Google Pay with Laravel Using APIs, you can follow these general steps:
- Set up a Google Pay API account:
- Go to the Google Pay API documentation.
- Follow the instructions to set up your Google Pay API account.
- Include the Google Pay API script in your Laravel project:
- In your Blade view or HTML file, include the Google Pay API script in the head section:
<head> <!-- Other head elements --> <script src="https://pay.google.com/gp/p/js/pay.js"></script> </head>
- Create a button to trigger the payment:
- Add a button to your view that will trigger the Google Pay payment:
<button id="google-pay-button">Pay with Google</button>
- Add a button to your view that will trigger the Google Pay payment:
- Implement the JavaScript code for Google Pay:
- Add a script section to your view or include a JavaScript file where you’ll implement the Google Pay logic:
<script> const base64url = (str) => btoa(str).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); const paymentDataRequest = { apiVersion: 2, apiVersionMinor: 0, allowedPaymentMethods: [{ type: 'CARD', parameters: { allowedAuthMethods: ['PAN_ONLY', 'CRYPTOGRAM_3DS'], allowedCardNetworks: ['VISA', 'MASTERCARD'] }, tokenizationSpecification: { type: 'PAYMENT_GATEWAY', parameters: { gateway: 'your_payment_gateway', gatewayMerchantId: 'your_merchant_id' } } }], merchantInfo: { merchantId: 'your_merchant_id', merchantName: 'Your Merchant Name' }, transactionInfo: { totalPriceStatus: 'FINAL', totalPriceLabel: 'Total', totalPrice: '100.00', currencyCode: 'USD', countryCode: 'US' } }; const paymentsClient = new google.payments.api.PaymentsClient({ environment: 'TEST' // Change to 'PRODUCTION' for live transactions }); document.getElementById('google-pay-button').addEventListener('click', () => { const paymentDataRequestWithParameters = Object.assign({}, paymentDataRequest); paymentDataRequestWithParameters.transactionInfo.totalPrice = '100.00'; // Update with your actual price paymentsClient.loadPaymentData(paymentDataRequestWithParameters) .then((paymentData) => { // Handle the successful payment response console.log(paymentData); }) .catch((error) => { // Handle errors console.error(error); }); }); </script>
- Replace
'your_payment_gateway'
and'your_merchant_id'
with your actual payment gateway and merchant ID.
- Handle the payment on the server side:Handling payments on the server side involves validating and processing the payment data received from the client (Google Pay in this case) and interacting with your payment gateway. Below is a basic example of how you might handle the payment on the server side using a Laravel controller:
- Create a controller: Create a new controller using the following Artisan command:
php artisan make:controller PaymentController
- Implement the payment handling logic in the controller: Open the
PaymentController
that was just created (app/Http/Controllers/PaymentController.php
) and add the following methods: <?php namespace App\Http\Controllers; use Illuminate\Http\Request; class PaymentController extends Controller { /** * Handle the payment confirmation from Google Pay. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function handlePaymentConfirmation(Request $request) { // Validate the request (you might want to add more validation) $request->validate([ 'paymentToken' => 'required', // Add other necessary validation rules ]); // Process the payment using your payment gateway $paymentToken = $request->input('paymentToken'); // Perform actions with the payment token (e.g., send it to the payment gateway) // Note: This is a simplified example, and you need to replace it with your actual payment gateway logic. // Example: $paymentGatewayResponse = $this->processPayment($paymentToken); // Check the payment gateway response and handle accordingly if ($paymentGatewayResponse['success']) { // Payment successful return response()->json(['message' => 'Payment successful']); } else { // Payment failed return response()->json(['message' => 'Payment failed', 'error' => $paymentGatewayResponse['error']], 400); } } /** * Simulate processing payment with your payment gateway. * * @param string $paymentToken * @return array */ private function processPayment($paymentToken) { // Implement your payment gateway integration logic here // This is a placeholder and should be replaced with your actual logic // Simulate a successful payment for demonstration purposes // Replace this with your actual payment gateway integration logic $success = true; $error = null; // Return a response return ['success' => $success, 'error' => $error]; } }
- Define routes for handling payment confirmation: Open the
routes/web.php
file and add the following route definition: use App\Http\Controllers\PaymentController; // Route for handling payment confirmation from Google Pay Route::post('/handle-payment-confirmation', [PaymentController::class, 'handlePaymentConfirmation']);
Adjust the route and controller method names as needed.
- Update the JavaScript code to send payment data to the server: Update the JavaScript code in your view to send the payment data to your Laravel backend:
// ... (previous JavaScript code) document.getElementById('google-pay-button').addEventListener('click', () => { const paymentDataRequestWithParameters = Object.assign({}, paymentDataRequest); paymentDataRequestWithParameters.transactionInfo.totalPrice = '100.00'; // Update with your actual price paymentsClient.loadPaymentData(paymentDataRequestWithParameters) .then((paymentData) => { // Send the payment data to the server for processing fetch('/handle-payment-confirmation', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ paymentToken: paymentData.paymentMethodData.tokenizationData.token }) }) .then(response => response.json()) .then(data => { // Handle the server response console.log(data); }) .catch(error => { // Handle errors console.error(error); }); }) .catch((error) => { // Handle errors console.error(error); }); });
Ensure that the URL (
'/handle-payment-confirmation'
) in thefetch
function corresponds to the route you defined in your Laravel routes file.
This is a simplified example, and you may need to adjust it based on your specific requirements and the payment gateway you are using. Always refer to the documentation of your payment gateway for accurate information on handling payments on the server side.
- Create a controller: Create a new controller using the following Artisan command:
Please note that this is a basic example, and you may need to adjust the code based on your specific requirements and the payment gateway you are using. Always refer to the official Google Pay API documentation and your payment gateway’s documentation for the most up-to-date and accurate information.
Conclusion
In conclusion, integrating Google Pay with Laravel can provide your users with a smooth and convenient payment experience, making your e-commerce platform more attractive and easy to use. By following these easy steps and using the provided code examples, you can easily integrate Google Pay with your Laravel application.
Recent Comments