Pembayaran Sekali Ketik dengan Tapak Web Anda: Buat Pembayaran Lebih Mudah dengan Google Pay

WBOY
Lepaskan: 2024-08-16 06:04:02
asal
712 orang telah melayarinya

Mengintegrasikan Google Pay dengan Tapak Web Anda: Panduan Langkah demi Langkah

Jika anda ingin menyepadukan Google Pay ke dalam tapak web anda untuk transaksi yang lancar, panduan ini akan membimbing anda melalui proses tersebut. Sama ada anda perniagaan kecil atau perusahaan besar, penyepaduan ini boleh membantu menyelaraskan proses pembayaran anda, menjadikannya lebih mudah untuk pelanggan menyelesaikan pembelian mereka.

Prasyarat:

Sebelum anda bermula, pastikan anda mempunyai perkara berikut:

  1. Pengesahan Pedagang: Pastikan perniagaan anda ialah pedagang UPI yang disahkan.
  2. Akses API: Dapatkan API yang diperlukan daripada bank anda untuk menyemak status pembayaran.
  3. ID Transaksi Unik: Setiap transaksi mesti menggunakan ID transaksi unik untuk memastikan pemprosesan selamat.

Proses Persediaan:

1. Daftar

Daftar perniagaan anda di Google Pay dan Wallet Console dan terima Syarat Perkhidmatan. Ini akan memberi anda akses kepada alatan yang anda perlukan untuk menyepadukan Google Pay dengan tapak web anda.

2. Buat Kaedah Pembayaran

Gunakan JavaScript untuk membuat objek kaedah pembayaran dengan medan UPI yang diperlukan seperti pa, pn, tr, mc dan am. Berikut ialah contoh:

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
  },
}];
Salin selepas log masuk

3. Tentukan Butiran Pesanan

Seterusnya, tentukan jumlah pesanan dan mata wang dalam objek butiran:

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

4. Buat Objek Permintaan Pembayaran

Bina objek PaymentRequest menggunakan kaedah pembayaran yang disokong dan butiran pesanan:

let request = new PaymentRequest(supportedInstruments, details);
Salin selepas log masuk

5. Semak Kesediaan Pembayaran

Gunakan kaedah canMakePayment() untuk mengesahkan sama ada pengguna boleh membuat pembayaran:

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

6. Tunjukkan UI Pembayaran

Mulakan proses pembayaran dengan memanggil kaedah show() pada objek PaymentRequest:

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

7. Mengendalikan Maklum Balas Pembayaran

Tukar respons pembayaran kepada JSON dan hantarkannya ke pelayan anda untuk pengesahan terhadap API bank anda:

function processResponse(paymentResponse) {
  fetch('/your-server-endpoint', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(paymentResponse)
  }).then(function(response) {
    // Handle server response
  });
}
Salin selepas log masuk

8. Pengesahan Pelayan

Akhir sekali, sahkan respons pembayaran dengan menyemak API bank anda untuk memastikan transaksi adalah sah sebelum memenuhi pesanan.

Menguji

Pastikan anda menguji pelaksanaan dengan teliti menggunakan Chrome untuk Android dan sahkan aliran transaksi dari permulaan hingga selesai.

Lihat tapak demo yang saya gunakan di Netlify. Walaupun anda tidak boleh membuat pembayaran kerana saya bukan pedagang, saya telah mengujinya menggunakan VPA Pedagang syarikat, dan ia berfungsi dengan baik.

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

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

Cabaran Seterusnya: Mengintegrasikan Google Pay dengan WooCommerce

Sebagai pembangun e-dagang, saya baru-baru ini menangani cabaran untuk menyepadukan Google Pay ke dalam tapak WooCommerce kami. Matlamat kami adalah untuk memudahkan proses pembayaran, menjadikannya lancar seperti pengalaman pengguna di platform utama seperti Flipkart.

Cabaran: Isu Peletakan Butang

Pada mulanya, kami menghadapi kesukaran meletakkan butang Google Pay pada halaman pembayaran. Ketua projek kami mencadangkan penyelesaian yang inovatif: bukannya butang berasingan, kami memutuskan untuk menyepadukan Google Pay sebagai pilihan butang radio lalai dalam kaedah pembayaran WooCommerce.

Pelaksanaan Kami - Aliran Niat UPI Google Pay dalam WooCommerce

Kami mencipta pemalam get laluan pembayaran tersuai untuk WooCommerce. Berikut ialah gambaran keseluruhan:

Prasyarat:

  • Tapak web WordPress dengan WooCommerce dipasang
  • Pengetahuan asas PHP dan JavaScript
  • Akses kepada tema WordPress anda dan fail pemalam

Langkah 1: Menyediakan Gerbang Pembayaran Tersuai

Buat gerbang pembayaran tersuai untuk Google Pay. Mulakan dengan mencipta fail baharu yang dipanggil custom-gateway.php dalam direktori pemalam anda:

<?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;
}
Salin selepas log masuk

Fail ini menyediakan struktur asas pemalam kami dan termasuk kelas get laluan utama.

Langkah 2: Mencipta Kelas Gateway

Sekarang, buat fail 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;
        }
    }
}
Salin selepas log masuk

Kelas ini memanjangkan get laluan pembayaran WooCommerce dan mengendalikan persediaan asas serta pemprosesan pembayaran Google Pay.

Langkah 3: Membuat Halaman Pemprosesan Pembayaran

Buat templat halaman baharu yang dipanggil page-payment-processing.php dalam direktori tema anda:

<?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>
Salin selepas log masuk

Templat halaman ini mengendalikan aliran Niat UPI Google Pay dan memproses pembayaran.

Langkah 4: Melaksanakan Integrasi Blok

Untuk memastikan keserasian dengan Blok WooCommerce, buat fail 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();
Salin selepas log masuk

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();
     }
    
    Salin selepas log masuk
  • 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
     }
    
    Salin selepas log masuk
  • 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.

Jika anda ingin meminimumkan yuran transaksi untuk perniagaan anda, menyepadukan Gpay untuk pembayaran UPI boleh menjadi penyelesaian yang menjimatkan kos.

Kesimpulan

Walaupun pelaksanaan kami mungkin tidak diperkemas seperti Flipkart, ia menyediakan penyelesaian praktikal untuk menyepadukan Google Pay ke dalam tapak WooCommerce. Ia mengimbangi fungsi dengan kekangan bekerja dalam ekosistem WordPress, menawarkan pelanggan pilihan pembayaran yang mudah tanpa memerlukan baik pulih lengkap proses pembayaran.

Melaksanakan aliran Google Pay UPI Intent dalam WordPress WooCommerce melibatkan beberapa langkah, daripada membuat get laluan pembayaran tersuai kepada pengendalian proses pembayaran dan memastikan keserasian dengan WooCommerce Blocks. Dengan mengikuti panduan ini, anda boleh menawarkan pilihan pembayaran yang lancar dan selamat kepada pelanggan anda menggunakan Google Pay.

Ingat untuk menguji secara menyeluruh dalam persekitaran pementasan sebelum digunakan ke tapak langsung anda. Selain itu, pastikan anda mematuhi semua piawaian dan peraturan keselamatan yang diperlukan semasa mengendalikan pembayaran.

Dengan memperhalusi pendekatan kami secara berterusan, kami berhasrat untuk mengecilkan jurang antara pelaksanaan kami dengan pemain e-dagang utama, sentiasa berusaha untuk memberikan pengalaman pengguna yang terbaik untuk pelanggan kami.

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

Selamat mengekod!

Atas ialah kandungan terperinci Pembayaran Sekali Ketik dengan Tapak Web Anda: Buat Pembayaran Lebih Mudah dengan Google Pay. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!