If you’re looking to integrate Google Pay into your website for seamless transactions, this guide will walk you through the process. Whether you're a small business or a large enterprise, this integration can help streamline your payment process, making it easier for customers to complete their purchases.
Before you begin, make sure you have the following in place:
Register your business on the Google Pay and Wallet Console and accept the Terms of Service. This will give you access to the tools you need to integrate Google Pay with your website.
Use JavaScript to create a payment method object with necessary UPI fields like pa, pn, tr, mc, and am. Here’s an example:
const supportedInstruments = [{ supportedMethods: 'https://tez.google.com/pay', data: { pa: 'merchant-vpa@xxx', pn: 'Merchant Name', tr: 'uniqueTransactionID', mc: '1234', // Merchant category code am: 'orderAmount', cu: 'INR', // Currency }, }];
Next, define the order amount and currency within a details object:
const details = { total: { label: 'Total', amount: { currency: 'INR', value: 'orderAmount' } } };
Construct a PaymentRequest object using the supported payment method and order details:
let request = new PaymentRequest(supportedInstruments, details);
Use the canMakePayment() method to verify if the user can make payments:
request.canMakePayment().then(function(result) { if (result) { // User can make payment } else { // Handle payment unavailability } });
Initiate the payment process by calling the show() method on the PaymentRequest object:
request.show().then(function(paymentResponse) { // Process the payment response }).catch(function(err) { console.error('Payment failed', err); });
Convert the payment response to JSON and send it to your server for validation against your bank’s API:
function processResponse(paymentResponse) { fetch('/your-server-endpoint', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(paymentResponse) }).then(function(response) { // Handle server response }); }
Finally, validate the payment response by checking with your bank’s API to ensure the transaction is legitimate before fulfilling the order.
Make sure to thoroughly test the implementation using Chrome for Android and verify the transaction flow from initiation to completion.
Check out the demo site I deployed on Netlify. While you can't make a payment since I'm not a merchant, I tested it using the company's Merchant VPA, and it works fine.
As an e-commerce developer, I recently tackled the challenge of integrating Google Pay into our WooCommerce site. Our goal was to simplify the payment process, making it as seamless as what users experience on major platforms like Flipkart.
Initially, we faced difficulties placing the Google Pay button on the checkout page. Our project lead suggested an innovative solution: instead of a separate button, we decided to integrate Google Pay as a default radio button option in the WooCommerce payment methods.
We created a custom payment gateway plugin for WooCommerce. Here’s an overview:
Create a custom payment gateway for Google Pay. Start by creating a new file called custom-gateway.php in your plugin directory:
<?php /* Plugin Name: Google Pay Description: Google Pay Payment integration for WooCommerce with custom payment selector. Version: 1.1.0 Author: Kamesh Author URI: Your website link/ Text Domain: google-pay-integration Domain Path: /languages */ add_action('plugins_loaded', 'woocommerce_myplugin', 0); function woocommerce_myplugin(){ if (!class_exists('WC_Payment_Gateway')) return; include(plugin_dir_path(__FILE__) . 'class-gateway.php'); } add_filter('woocommerce_payment_gateways', 'add_my_custom_gateway'); function add_my_custom_gateway($gateways) { $gateways[] = 'My_Custom_Gateway'; return $gateways; }
This file sets up the basic structure of our plugin and includes the main gateway class.
Now, create the class-gateway.php file:
<?php class My_Custom_Gateway extends WC_Payment_Gateway { public function __construct() { $this->id = 'my_custom_gateway'; $this->method_title = __('Google Pay', 'my-custom-gateway'); $this->method_description = __('Accept payments through Google Pay', 'my-custom-gateway'); $this->init_form_fields(); $this->init_settings(); $this->title = $this->get_option('title'); $this->description = $this->get_option('description'); $this->icon = plugins_url('/asset/GPay_Acceptance_Mark_800.png', __FILE__); if (!$this->is_android_device()) { $this->enabled = 'no'; } if ($this->is_gsa_device()) { $this->enabled = 'no'; } } public function process_payment($order_id) { $order = wc_get_order($order_id); $order->update_status('pending', __('Awaiting Google Pay payment', 'my-custom-gateway')); $processing_page = get_page_by_path('payment-processing'); if ($processing_page) { return array( 'result' => 'success', 'redirect' => add_query_arg('order_id', $order_id, get_permalink($processing_page->ID)), ); } else { wc_add_notice(__('Payment processing page not found. Please contact the administrator.', 'my-custom-gateway'), 'error'); return; } } }
This class extends the WooCommerce payment gateway and handles the basic setup and processing of the Google Pay payment.
Create a new page template called page-payment-processing.php in your theme directory:
<?php /* Template Name: Payment Processing */ ?> <!DOCTYPE html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo('charset'); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Processing Payment</title> <?php wp_head(); ?> </head> <body> <script> jQuery(document).ready(function($) { var orderId = <?php echo $order_id; ?>; var isProcessing = true; function handlePayAndroid(orderId, price) { const amount = Number(price); if (!window.PaymentRequest) { console.log('Web payments are not supported in this browser.'); return; } const supportedInstruments = [{ supportedMethods: ['https://tez.google.com/pay'], data: { pa: 'merchant-vpa@xxx', pn: 'Merchant Name', tr: generateTransactionReferenceID(),//replace with your generating transaction id url: '<?php echo add_query_arg('order_id', "' + orderId + '", get_permalink(page id)); ?>',//replace with your actual page id mc: '5977', tn: orderId, }, }]; const details = { total: { label: 'Total (including shipping)', amount: { currency: 'INR', value: amount.toFixed(2) } }, }; } handlePay(orderId); }); </script> <?php wp_footer(); ?> </body> </html>
This page template handles the Google Pay UPI Intent flow and processes the payment.
To ensure compatibility with WooCommerce Blocks, create a class-block.php file:
<?php use Automattic\WooCommerce\Blocks\ Payments\Integrations\AbstractPaymentMethodType; class WC_Google_Pay_Integration extends AbstractPaymentMethodType { public function initialize() { // Set up the payment method integration add_filter('woocommerce_blocks_payment_method_type_registration', function ($gateways) { $gateways['google_pay'] = $this; return $gateways; }); } public function get_name() { return 'google_pay'; } public function is_active() { return true; } } $wc_google_pay_integration = new WC_Google_Pay_Integration(); $wc_google_pay_integration->initialize();
Test the plugin in your staging environment before deploying it to production. Ensure that all functionalities work as expected, especially the payment processing page.
Integrating Google Pay with your WooCommerce site can greatly enhance your customer’s shopping experience by providing them with a faster, more secure payment option. With this integration, you can simplify the checkout process and potentially increase your conversion rates.
This blog post covers the essential steps to integrate Google Pay into a website and WooCommerce, along with the challenges and solutions I encountered during the process.
While our solution achieves the goal of integrating Google Pay, there are some differences compared to how Flipkart handle one-tap payments:
While our implementation differs from major e-commerce platforms, it offers several benefits:
Official Documentation link
Automatically Generate a Transaction ID:
function generateTransactionReferenceID() { return 'TXN' + Math.random().toString(36).substr(2, 9).toUpperCase(); }
Compatibility Handling:
if (!window.PaymentRequest || !navigator.userAgent.includes('Android')) { // Disable Google Pay option }
Razorpay and PhonePe charge a fee of 2% + GST on all successful transactions.
Regarding Google Pay (Gpay), it can indeed offer lower transaction fees, especially for UPI-based transactions. UPI transactions typically have lower or no fees, which can help reduce overall costs compared to traditional payment gateways.
If you’re looking to minimize transaction fees for your business, integrating Gpay for UPI payments could be a cost-effective solution.
While our implementation may not be as streamlined as Flipkart's it provides a practical solution for integrating Google Pay into a WooCommerce site. It balances functionality with the constraints of working within the WordPress ecosystem, offering customers a convenient payment option without requiring a complete overhaul of the checkout process.
Implementing the Google Pay UPI Intent flow in WordPress WooCommerce involves several steps, from creating a custom payment gateway to handling the payment process and ensuring compatibility with WooCommerce Blocks. By following this guide, you can offer your customers a seamless and secure payment option using Google Pay.
Remember to test thoroughly in a staging environment before deploying to your live site. Also, ensure that you comply with all necessary security standards and regulations when handling payments.
By continuously refining our approach, we aim to narrow the gap between our implementation and those of major e-commerce players, always striving to provide the best possible user experience for our customers.
Happy coding!
The above is the detailed content of One-Tap Payment with Your Website: Make Payments Easier with Google Pay. For more information, please follow other related articles on the PHP Chinese website!