首页  >  文章  >  web前端  >  通过您的网站一键式付款:使用 Google Pay 让付款更轻松

通过您的网站一键式付款:使用 Google Pay 让付款更轻松

WBOY
WBOY原创
2024-08-16 06:04:02712浏览

将 Google Pay 与您的网站集成:分步指南

如果您希望将 Google Pay 集成到您的网站中以实现无缝交易,本指南将引导您完成整个过程。无论您是小型企业还是大型企业,这种集成都可以帮助简化您的支付流程,让客户更轻松地完成购买。

先决条件:

开始之前,请确保满足以下条件:

  1. 商户验证:确保您的企业是经过验证的 UPI 商户。
  2. API 访问:从您的银行获取必要的 API 以检查付款状态。
  3. 唯一交易ID:每笔交易都必须使用唯一的交易ID以确保安全处理。

设置过程:

1. 注册

在 Google Pay 和电子钱包控制台上注册您的公司并接受服务条款。这将使您能够访问将 Google Pay 与您的网站集成所需的工具。

2. 创建付款方式

使用 JavaScript 创建一个付款方式对象,其中包含必要的 UPI 字段,如 pa、pn、tr、mc 和 am。这是一个例子:

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
  },
}];

3. 定义订单详细信息

接下来,在详细信息对象中定义订单金额和货币:

const details = {
  total: {
    label: 'Total',
    amount: { currency: 'INR', value: 'orderAmount' }
  }
};

4. 创建支付请求对象

使用支持的付款方式和订单详细信息构造 PaymentRequest 对象:

let request = new PaymentRequest(supportedInstruments, details);

5. 检查付款准备情况

使用canMakePayment()方法验证用户是否可以付款:

request.canMakePayment().then(function(result) {
  if (result) {
    // User can make payment
  } else {
    // Handle payment unavailability
  }
});

6. 显示支付界面

通过调用 PaymentRequest 对象上的 show() 方法来启动付款流程:

request.show().then(function(paymentResponse) {
  // Process the payment response
}).catch(function(err) {
  console.error('Payment failed', err);
});

7. 处理付款响应

将付款响应转换为 JSON 并将其发送到您的服务器以根据银行的 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
  });
}

8. 服务器验证

最后,在履行订单之前,通过检查银行的​​ API 来验证付款响应,以确保交易合法。

测试

确保使用 Android 版 Chrome 彻底测试实现,并验证从启动到完成的交易流程。

查看我在 Netlify 上部署的演示站点。虽然我不是商家所以无法付款,但我使用公司的商家VPA进行了测试,效果很好。

One-Tap Payment with Your Website: Make Payments Easier with Google Pay

One-Tap Payment with Your Website: Make Payments Easier with Google Pay

下一个挑战:将 Google Pay 与 WooCommerce 集成

作为一名电子商务开发人员,我最近解决了将 Google Pay 集成到我们的 WooCommerce 网站中的挑战。我们的目标是简化支付流程,使其与用户在 Flipkart 等主要平台上的体验一样无缝。

挑战:按钮放置问题

最初,我们在将 Google Pay 按钮放置在结帐页面上时遇到了困难。我们的项目负责人提出了一个创新的解决方案:我们决定将 Google Pay 作为默认单选按钮选项集成到 WooCommerce 付款方式中,而不是单独的按钮。

我们的实施 - WooCommerce 中的 Google Pay UPI 意图流

我们为 WooCommerce 创建了一个自定义支付网关插件。概述如下:

先决条件:

  • 安装了 WooCommerce 的 WordPress 网站
  • PHP 和 JavaScript 基础知识
  • 访问您的 WordPress 主题和插件文件

第 1 步:设置自定义支付网关

为 Google Pay 创建自定义支付网关。首先在插件目录中创建一个名为 custom-gateway.php 的新文件:

f7fbf99d23697c8c8c0c13645992444did = '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;
        }
    }
}

此类扩展了 WooCommerce 支付网关并处理 Google Pay 付款的基本设置和处理。

第 3 步:创建付款处理页面

在主题目录中创建一个名为 page- payment-processing.php 的新页面模板:

a7feada9eb7f71b300d1c3e8d6df2189
8b05045a5be5764f313ed5b9168a17e6
b13368972aeac97478d0803d09e46821>
93f0f5c25f18dab9d176bd4f6de5d30e
    015fa40513e621834c1519954d608eec">
    e6a2ef4717ed03faee9e40cd54c601e7
    b2386ffb911b14667cb8f0f91ea547a7Processing Payment6e916e0f7d1e588d4f442bf645aedb2f
    12493c822e68bbb57c539d2976ef876e
9c3bca370b5104690d9ef395f2c5f8d1
6c04bd5ca3fcae76e30b72ad730ca86d
    3f1c4e4b6b16bbbd69b2ee476dc4f83a
        jQuery(document).ready(function($) {
            var orderId = 6dabfbaeea0bf0ad6da6f153c156da04;
            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: '1dc361a8189e423757ceb255006efd0f',//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);
        });
    2cacc6d41bbb37262a98f745aa00fbf0
    64e84f45db36f5bcd4aecd6dd796a396
36cc49f0c466276486e50c850b7e4956
73a6ac4ed44ffec12cee46588e518a5e

此页面模板处理 Google Pay UPI 意图流并处理付款。

第 4 步:实施块集成

为了确保与 WooCommerce 块的兼容性,请创建一个 class-block.php 文件:

94cbd21ce53ac994e84c4c4735887c39initialize();

Step 5 : Testing and Deployment

Test the plugin in your staging environment before deploying it to production. Ensure that all functionalities work as expected, especially the payment processing page.

One-Tap Payment with Your Website: Make Payments Easier with Google Pay

Here i didn't attach the Successful payment in the gpay because of the security

One-Tap Payment with Your Website: Make Payments Easier with Google Pay

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.

Comparison with Flipkart

While our solution achieves the goal of integrating Google Pay, there are some differences compared to how Flipkart handle one-tap payments:

One-Tap Payment with Your Website: Make Payments Easier with Google Pay
One-Tap Payment with Your Website: Make Payments Easier with Google Pay

Payment Flow:

  • Redirects to a separate processing page, which may add an extra step but allows for more control over the payment flow.

Integration Depth:

  • Flipkart : Likely have deeper integration with Google Pay's API, possibly using advanced features.
  • Our Solution: Uses the standard Web Payment Request API, which is more accessible for smaller e-commerce sites but may lack some advanced features.

Advantages of Our Approach

While our implementation differs from major e-commerce platforms, it offers several benefits:

  1. Ease of Integration: Works within the existing WooCommerce framework.
  2. Flexibility: Can be easily adapted to different WooCommerce themes.
  3. Familiar UX: Maintains consistency with other WooCommerce payment methods.
  4. Cost-Effective: Doesn't require extensive custom development.

Official Documentation link

Additional Features

  1. Automatically Generate a Transaction ID:

    • Ensuring each transaction has a unique ID is crucial for tracking and validating payments. In our implementation, the transaction ID is automatically generated using a custom function. This ensures that no two transactions have the same identifier, which is vital for both security and record-keeping.
    • Example:
     function generateTransactionReferenceID() {
         return 'TXN' + Math.random().toString(36).substr(2, 9).toUpperCase();
     }
    
  • This function generates a unique alphanumeric string that can be used as a transaction reference ID for each payment.
  1. Compatibility Handling:

    • The Google Pay implementation provided in their documentation is primarily compatible with Chrome on Android devices. To ensure a smooth user experience, we’ve implemented a feature that disables Google Pay for non-compatible devices automatically. This prevents users on unsupported platforms from encountering errors or issues during the checkout process.
    • Example:
     if (!window.PaymentRequest || !navigator.userAgent.includes('Android')) {
         // Disable Google Pay option
     }
    
  • This check ensures that the Google Pay option is only available for users on compatible devices, providing a seamless payment experience.
  1. Bank API and Google Pay Issues:
    • During our implementation, we encountered some issues with the bank's API and Google Pay integration. To address this, we reached out to the Google Pay developer team for support. The team is currently investigating the issue, and we are working closely with them to resolve it. Despite these challenges, the integration has been successful and has already generated approximately ₹1 lakh in revenue within the first week.
    • This emphasizes the importance of ongoing support and communication with service providers when integrating complex payment solutions.

Transaction Fees:

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.

Conclusion

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.

One-Tap Payment with Your Website: Make Payments Easier with Google Pay

Happy coding!

以上是通过您的网站一键式付款:使用 Google Pay 让付款更轻松的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn