首頁 > web前端 > js教程 > 主體

透過您的網站一鍵式付款:使用 Google Pay 讓付款更輕鬆

WBOY
發布: 2024-08-16 06:04:02
原創
712 人瀏覽過

將 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 的新檔案:

<?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;
}
登入後複製

此文件設定了我們插件的基本結構,並包含主網關類別。

第 2 步:建立網關類

現在,建立 class-gateway.php 檔案:

<?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;
        }
    }
}
登入後複製

此類擴展了 WooCommerce 支付網關並處理 Google Pay 付款的基本設定和處理。

第 3 步:建立付款處理頁面

在主題目錄中建立一個名為 page- payment-processing.php 的新頁面範本:

<?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>
登入後複製

此頁面範本處理 Google Pay UPI 意圖流並處理付款。

第 4 步:實施區塊集成

為了確保與 WooCommerce 區塊的相容性,請建立一個 class-block.php 檔案:

<?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();
登入後複製

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.

如果您希望最大限度地降低企业的交易费用,集成 Gpay 进行 UPI 支付可能是一种经济高效的解决方案。

结论

虽然我们的实施可能不像 Flipkart 那样简化,但它提供了将 Google Pay 集成到 WooCommerce 网站的实用解决方案。它平衡了功能与 WordPress 生态系统内工作的限制,为客户提供了便捷的支付选项,而无需彻底修改结账流程。

在 WordPress WooCommerce 中实现 Google Pay UPI 意图流程涉及多个步骤,从创建自定义支付网关到处理支付流程以及确保与 WooCommerce 块的兼容性。通过遵循本指南,您可以使用 Google Pay 为您的客户提供无缝且安全的付款选项。

请记住在部署到实际站点之前在临时环境中进行彻底测试。另外,请确保您在处理付款时遵守所有必要的安全标准和法规。

通过不断完善我们的方法,我们的目标是缩小我们的实施与主要电子商务参与者之间的差距,始终努力为我们的客户提供最佳的用户体验。

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

编码愉快!

以上是透過您的網站一鍵式付款:使用 Google Pay 讓付款更輕鬆的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!