웹사이트를 통한 원탭 결제: 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 및 Wallet 콘솔에 비즈니스를 등록하고 서비스 약관에 동의하세요. 이를 통해 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 통합

저는 전자상거래 개발자로서 최근 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-pay-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 블록과의 호환성 보장까지 여러 단계가 필요합니다. 이 가이드를 따르면 고객에게 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 학습자의 빠른 성장을 도와주세요!