ウェブサイトでのワンタップ支払い: 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 and Wallet Console にビジネスを登録し、利用規約に同意します。これにより、Google Pay をウェブサイトに統合するために必要なツールにアクセスできるようになります。

2. 支払い方法の作成

JavaScript を使用して、pa、pn、tr、mc、am などの必要な UPI フィールドを含む支払い方法オブジェクトを作成します。以下に例を示します:

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. 支払い UI を表示する

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 の統合

私は最近、e コマース開発者として、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 Blocks との互換性を確保するには、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.

ビジネスの取引手数料を最小限に抑えたい場合は、UPI 支払いに Gpay を統合することが費用対効果の高いソリューションとなる可能性があります。

結論

私たちの実装は Flipkart ほど合理化されていないかもしれませんが、Google Pay を WooCommerce サイトに統合するための実用的なソリューションを提供します。機能性と WordPress エコシステム内での作業の制約のバランスをとり、チェックアウトプロセスの全面的な見直しを必要とせずに、便利な支払いオプションを顧客に提供します。

WordPress WooCommerce で Google Pay UPI インテント フローを実装するには、カスタム支払いゲートウェイの作成から支払いプロセスの処理、WooCommerce Blocks との互換性の確保まで、いくつかの手順が必要です。このガイドに従うことで、Google Pay を使用したシームレスで安全な支払いオプションを顧客に提供できます。

ライブサイトに展開する前に、ステージング環境で徹底的にテストすることを忘れないでください。また、支払いを処理する際には、必要なセキュリティ基準と規制をすべて遵守するようにしてください。

当社のアプローチを継続的に改良することで、当社の実装と主要な e コマース プレーヤーの実装とのギャップを縮め、お客様に可能な限り最高のユーザー エクスペリエンスを提供できるよう常に努めています。

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

コーディングを楽しんでください!

以上がウェブサイトでのワンタップ支払い: Google Pay で支払いを簡単にの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!