在 Woocommerce 中添加带有附加单选按钮的自定义支付网关

2023-12-25

我正在为 woocommerce 开发自定义付款方式,下面是我的代码:

class WC_Gateway_Custom extends WC_Payment_Gateway {

    public $domain;

    /**
     * Constructor for the gateway.
     */
    public function __construct() {

        $this->domain = 'custom_payment';

        $this->id                 = 'custom';
        $this->icon               = apply_filters('woocommerce_custom_gateway_icon', '');
        $this->has_fields         = false;
        $this->method_title       = __( 'Custom', $this->domain );
        $this->method_description = __( 'Allows payments with custom gateway.', $this->domain );

        // Load the settings.
        $this->init_form_fields();
        $this->init_settings();

        // Define user set variables
        $this->title        = $this->get_option( 'title' );
        $this->description  = $this->get_option( 'description' );
        $this->instructions = $this->get_option( 'instructions', $this->description );
        $this->order_status = $this->get_option( 'order_status', 'completed' );

        // Actions
        add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
        add_action( 'woocommerce_thankyou_custom', array( $this, 'thankyou_page' ) );

        // Customer Emails
        add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
    }

    /**
     * Initialise Gateway Settings Form Fields.
     */
    public function init_form_fields() {

        $this->form_fields = array(
            'enabled' => array(
                'title'   => __( 'Enable/Disable', $this->domain ),
                'type'    => 'checkbox',
                'label'   => __( 'Enable Custom Payment', $this->domain ),
                'default' => 'yes'
            ),
            'title' => array(
                'title'       => __( 'Title', $this->domain ),
                'type'        => 'text',
                'description' => __( 'This controls the title which the user sees during checkout.', $this->domain ),
                'default'     => __( 'Custom Payment', $this->domain ),
                'desc_tip'    => true,
            ),
            'order_status' => array(
                'title'       => __( 'Order Status', $this->domain ),
                'type'        => 'select',
                'class'       => 'wc-enhanced-select',
                'description' => __( 'Choose whether status you wish after checkout.', $this->domain ),
                'default'     => 'wc-completed',
                'desc_tip'    => true,
                'options'     => wc_get_order_statuses()
            ),
            'description' => array(
                'title'       => __( 'Description', $this->domain ),
                'type'        => 'textarea',
                'description' => __( 'Payment method description that the customer will see on your checkout.', $this->domain ),
                'default'     => __('Payment Information', $this->domain),
                'desc_tip'    => true,
            ),
            'instructions' => array(
                'title'       => __( 'Instructions', $this->domain ),
                'type'        => 'textarea',
                'description' => __( 'Instructions that will be added to the thank you page and emails.', $this->domain ),
                'default'     => '',
                'desc_tip'    => true,
            ),
        );
    }

    /**
     * Output for the order received page.
     */
    public function thankyou_page() {
        if ( $this->instructions )
            echo wpautop( wptexturize( $this->instructions ) );
    }

    /**
     * Add content to the WC emails.
     *
     * @access public
     * @param WC_Order $order
     * @param bool $sent_to_admin
     * @param bool $plain_text
     */        

    public function payment_fields(){

        if ( $description = $this->get_description() ) {
            echo wpautop( wptexturize( $description ) );
        }
        echo 'added custom field in radio buttons';
     /**
     * Process the payment and return the result.
     *
     * @param int $order_id
     * @return array
     */
    }
    public function generate_form($order_id){
        global $woocommerce;

    // Get this Order's information so that we know
    // who to charge and how much
    $customer_order = new WC_Order($order_id);

    $_instructions     = $this->instructions;
    $_order_status    = $this->order_status;


    $items = $customer_order->get_items();
    $product_name  = array();
    foreach ( $items as $item ) {
        array_push($product_name, $item['name']);
    }
    $_Description   = implode(", ", $product_name);
    echo 'here i want to get the value selected by the customer from front end';
    //here is the part where i want to get the value of form inside payment_fields() fucntion 
    exit;   
    } 

}

我需要设置我的自定义付款方式的交易类型并附上屏幕截图以便更好地理解,请参阅:

没有关于如何覆盖此 payment_fields() 函数的帮助,我可以打印 html,但不知道如何获取该值并将其设置为订单的交易类型


您的代码中存在一些错误、错误和缺失的内容……这是一个完整的插件文件,当在结账页面中选择它时,它可以添加到网关上的“特殊”付款单选按钮。

所选的“交易类型”单选按钮值将作为自定义元数据保存在订单中。

所选的“交易类型”值将显示在:

  • 订单已收到页面,我的帐户 > 查看订单
  • 管理员编辑订单页面
  • 关于电子邮件通知

在订单查看页面上:

这是完整的插件代码:

<?php
/**
 * Plugin Name: WooCommerce Special Payment Gateway
 * Plugin URI:
 * Description: custom Special payment method.
 * Author: Me
 * Author URI: http://www.something.tld/
 * Version: 1.1.0
 * Text Domain: wcpg-special
 * Domain Path: /i18n/languages/
 *
 * Copyright: (c) 2018
 *
 * License: GNU General Public License v3.0
 * License URI: http://www.gnu.org/licenses/gpl-3.0.html
 *
 * @package   wcpg-special
 * @author    Me
 * @category  Admin
 * @copyright Copyright (c)  2016-2018
 * @license   http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License v3.0
 */
defined( 'ABSPATH' ) or exit;
// Make sure WooCommerce is active
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    return;
}
/**
 * Add the gateway to WC Available Gateways
 *
 * @since 1.0.0
 * @param array $gateways all available WC gateways
 * @return array $gateways all WC gateways + Custom Special gateway
 */
function wc_add_special_to_gateways( $gateways ) {
    $gateways[] = 'WC_Gateway_Special';
    return $gateways;
}
add_filter( 'woocommerce_payment_gateways', 'wc_add_special_to_gateways' );
/**
 * Adds plugin page links
 *
 * @since 1.0.0
 * @param array $links all plugin links
 * @return array $links all plugin links + our custom links (i.e., "Settings")
 */
function wc_special_gateway_plugin_links( $links ) {
    $plugin_links = array(
        '<a href="' . admin_url( 'admin.php?page=wc-settings&tab=checkout&section=special_payment' ) . '">' . __( 'Configure', 'wcpg-special' ) . '</a>'
    );
    return array_merge( $plugin_links, $links );
}
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), 'wc_special_gateway_plugin_links' );
/**
 * Custom Payment Gateway
 *
 * Provides an Custom Payment Gateway; mainly for testing purposes.
 * We load it later to ensure WC is loaded first since we're extending it.
 *
 * @class       WC_Gateway_Special
 * @extends     WC_Payment_Gateway
 * @version     1.0.0
 * @package     WooCommerce/Classes/Payment
 * @author      Me
 */
add_action( 'plugins_loaded', 'wc_special_gateway_init', 11 );
function wc_special_gateway_init() {
    class WC_Gateway_Special extends WC_Payment_Gateway {

        public $domain;

        /**
         * Constructor for the gateway.
         */
        public function __construct() {
            $this->id                 = 'special_payment';
            $this->domain             = 'wcpg-special';
            $this->icon               = apply_filters('woocommerce_payment_gateway_icon', '');
            $this->has_fields         = false;
            $this->method_title       = __( 'Custom Payment', $this->domain );

            // Define "payment type" radio buttons options field
            $this->options = array(
                'type1' => __( 'Type 1', $this->domain ),
                'type2' => __( 'Type 2', $this->domain ),
                'type3' => __( 'Type 3', $this->domain ),
            );

            // Load the settings.
            $this->init_form_fields();
            $this->init_settings();

            // Define user set variables
            $this->title        = $this->get_option( 'title' );
            $this->description  = $this->get_option( 'description' );
            $this->instructions = $this->get_option( 'instructions' );
            $this->order_status = $this->get_option( 'order_status' );
            $this->status_text  = $this->get_option( 'status_text' );

            // Actions
            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
            add_action( 'woocommerce_checkout_create_order', array( $this, 'save_order_payment_type_meta_data' ), 10, 2 );
            add_filter( 'woocommerce_get_order_item_totals', array( $this, 'display_transaction_type_order_item_totals'), 10, 3 );
            add_action( 'woocommerce_admin_order_data_after_billing_address',  array( $this, 'display_payment_type_order_edit_pages'), 10, 1 );
            add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'thankyou_page' ) );

            // Customer Emails
            add_action( 'woocommerce_email_before_order_table', array( $this, 'email_instructions' ), 10, 3 );
        }
        /**
         * Initialize Gateway Settings Form Fields
         */
        public function init_form_fields() {
            $this->form_fields = apply_filters( 'wc_special_payment_form_fields', array(
                'enabled' => array(
                    'title'   => __( 'Enable/Disable', $this->domain ),
                    'type'    => 'checkbox',
                    'label'   => __( 'Enable Special Payment', $this->domain ),
                    'default' => 'yes'
                ),
                'title' => array(
                    'title'       => __( 'Title', $this->domain ),
                    'type'        => 'text',
                    'description' => __( 'This controls the title for the payment method the customer sees during checkout.', $this->domain ),
                    'default'     => __( 'Special Payment', $this->domain ),
                    'desc_tip'    => true,
                ),
                'description' => array(
                    'title'       => __( 'Description', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Payment method description that the customer will see on your checkout.', $this->domain ),
                    'default'     => __( 'Please remit payment to Store Name upon pickup or delivery.', $this->domain ),
                    'desc_tip'    => true,
                ),
                'instructions' => array(
                    'title'       => __( 'Instructions', $this->domain ),
                    'type'        => 'textarea',
                    'description' => __( 'Instructions that will be added to the thank you page and emails.', $this->domain ),
                    'default'     => '', // Empty by default
                    'desc_tip'    => true,
                ),
                'order_status' => array(
                    'title'       => __( 'Order Status', $this->domain ),
                    'type'        => 'select',
                    'description' => __( 'Choose whether order status you wish after checkout.', $this->domain ),
                    'default'     => 'wc-completed',
                    'desc_tip'    => true,
                    'class'       => 'wc-enhanced-select',
                    'options'     => wc_get_order_statuses()
                ),
                'status_text' => array(
                    'title'       => __( 'Order Status Text', $this->domain ),
                    'type'        => 'text',
                    'description' => __( 'Set the text for the selected order status.', $this->domain ),
                    'default'     => __( 'Order is completed', $this->domain ),
                    'desc_tip'    => true,
                ),
            ) );
        }

        /**
         * Output the "payment type" radio buttons fields in checkout.
         */
        public function payment_fields(){
            if ( $description = $this->get_description() ) {
                echo wpautop( wptexturize( $description ) );
            }

            echo '<style>#transaction_type_field label.radio { display:inline-block; margin:0 .8em 0 .4em}</style>';

            $option_keys = array_keys($this->options);

            woocommerce_form_field( 'transaction_type', array(
                'type'          => 'radio',
                'class'         => array('transaction_type form-row-wide'),
                'label'         => __('Payment Information', $this->domain),
                'options'       => $this->options,
            ), reset( $option_keys ) );
        }

        /**
         * Save the chosen payment type as order meta data.
         *
         * @param object $order
         * @param array $data
         */
        public function save_order_payment_type_meta_data( $order, $data ) {
            if ( $data['payment_method'] === $this->id && isset($_POST['transaction_type']) )
                $order->update_meta_data('_transaction_type', esc_attr($_POST['transaction_type']) );
        }

        /**
         * Output for the order received page.
         *
         * @param int $order_id
         */
        public function thankyou_page( $order_id ) {
            $order = wc_get_order( $order_id );

            if ( $this->instructions ) {
                echo wpautop( wptexturize( $this->instructions ) );
            }
        }

        /**
         * Display the chosen payment type on the order edit pages (backend)
         *
         * @param object $order
         */
        public function display_payment_type_order_edit_pages( $order ){
            if( $this->id === $order->get_payment_method() && $order->get_meta('_transaction_type') ) {
                $options  = $this->options;
                echo '<p><strong>'.__('Transaction type').':</strong> ' . $options[$order->get_meta('_transaction_type')] . '</p>';
            }
        }

        /**
         * Display the chosen payment type on order totals table
         *
         * @param array    $total_rows
         * @param WC_Order $order
         * @param bool     $tax_display
         * @return array
         */
        public function display_transaction_type_order_item_totals( $total_rows, $order, $tax_display ){
            if( is_a( $order, 'WC_Order' ) && $order->get_meta('_transaction_type') ) {
                $new_rows = []; // Initializing
                $options  = $this->options;

                // Loop through order total lines
                foreach( $total_rows as $total_key => $total_values ) {
                    $new_rows[$total_key] = $total_values;
                    if( $total_key === 'payment_method' ) {
                        $new_rows['payment_type'] = [
                            'label' => __("Transaction type", $this->domain) . ':',
                            'value' => $options[$order->get_meta('_transaction_type')],
                        ];
                    }
                }

                $total_rows = $new_rows;
            }
            return $total_rows;
        }

        /**
         * Add content to the WC emails.
         *
         * @access public
         * @param WC_Order $order
         * @param bool $sent_to_admin
         * @param bool $plain_text
         */
        public function email_instructions( $order, $sent_to_admin, $plain_text = false ) {
            if ( $this->instructions && ! $sent_to_admin && $this->id === $order->get_payment_method()
            && $order->has_status( $this->order_status ) ) {
                echo wpautop( wptexturize( $this->instructions ) ) . PHP_EOL;
            }
        }

        /**
         * Process the payment and return the result
         *
         * @param int $order_id
         * @return array
         */
        public function process_payment( $order_id ) {
            $order = wc_get_order( $order_id );

            // Mark as on-hold (we're awaiting the payment)
            $order->update_status( $this->order_status, $this->status_text );

            // Reduce stock levels
            wc_reduce_stock_levels( $order->get_id() );

            // Remove cart
            WC()->cart->empty_cart();

            // Return thankyou redirect
            return array(
                'result'    => 'success',
                'redirect'  => $this->get_return_url( $order )
            );
        }
    }
}

代码作为插件 php 文件输入,您可以根据需要命名该文件(并可选择将其包含在文件夹中)。压缩文件(或文件夹)并通过 Wordpress 将其添加为插件。激活它。

经过测试并有效。

关于电子邮件通知:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Woocommerce 中添加带有附加单选按钮的自定义支付网关 的相关文章

  • 如何检查号码是否是巴基斯坦用户的手机号码而不是固定电话号码

    我所做的是从开头删除 92 或 0092 并使用以下代码检查它是否是巴基斯坦人的有效手机号码 if preg match 3 0 4 0 9 number 1 Pakistani mobile number else not a pakis
  • PHP 文件上传帮助

    div align center div 这是我的代码
  • cURL 错误 77:设置证书验证位置时出错:CAfile

    我正在使用 Firebase php SDKlink https firebase php readthedocs io en latest index html并在 Windows 10 上的 XAMPP 服务器上使用 laravel 最
  • 如何在 Zend Framework 中存储 cron 作业的脚本?

    因为 ZF 的所有 URL 都依赖于 mod 重写 所以我并不清楚应该在哪里存储用于 cron 作业的本地脚本 有人有什么建议 或者有 正式接受 的方式吗 我用模块化目录结构 http framework zend com manual e
  • 按类别 ID 获取产品

    我正在为 woocommerce 编写一个定价表插件 用户插入带有 woocommerce 产品类别 ID 的短代码 更新页面后 用户可以看到一个包含产品名称和价格列表的表格 我怎样才能获得带有类别ID的产品列表 在下面的代码中 pid是用
  • 运行 Composer 返回:“无法打开输入文件:composer.phar”

    我是 symfony2 和阅读新手symblog http tutorial symblog co uk tutorial parts 在第三章中 在尝试使用数据装置时 我尝试了以下命令 php composer phar update 但
  • 使用 PHP 将值插入可编辑 PDF,并保持可编辑状态

    我有一个带有可编辑字段的 PDF 我希望将 HTML 表单中的值传递到此 PDF 中 我尝试过使用 FPDF 并且它有效 但是将值传递到 PDF 后 pdf 中的字段不再可编辑 另一个缺点是 在将值传递到 PDF 时 我们必须为每个字段指定
  • 在Wordpress中通过API创建新用户时如何发送电子邮件密码?

    可以使用以下行通过 API 创建新用户 user id wp insert user user data 我想知道如何向新创建的用户发送包含其密码的电子邮件 Wordpress API 中是否有任何函数可以处理这项工作 还是我应该自己创建并
  • php 如何统计文件夹中的文件数量?

    我想让用户能够在自己的文件夹中上传一些文件 图片 但只有当该文件夹包含的图片少于五张时才可能 如果已经有 5 张图片 脚本必须让用户知道他 她的文件夹已满 所以 我想知道php中是否有函数可以计算文件夹中的文件数量 或者 php 中有其他方
  • 使用 php 更改白天和黑夜的背景?

    我正在制作一个 tumblr 页面 我的 html 页面有两种不同的背景 我希望白天背景从早上 7 点到晚上 8 点显示 夜间背景从晚上 8 点到早上 7 点显示 我决定用 php 来做这件事 但对于 php 来说我是个新手 我的朋友给我发
  • TOMCAT 6 中的 PHP - 异常

    我一直在努力融入PHP in APACHE TOMCAT 6依照指示second answer为了QUESTION https stackoverflow com questions 779246 run a php app using t
  • 将函数中的会话变量传递给 codeigniter 中的助手

    这就是我正在尝试做的事情 这是控制器中的功能 public function get started if test login this gt session gt all userdata this gt load gt view te
  • PHP 中的 Preg_replace

    我想替换 中包含的字符串中的内容content 它是多行等 preg replace 函数应该删除整个 com 没有垫子 蒙特 尝试这个 result preg replace s replacement content subject
  • PHP 中的 NOW() 函数

    是否有 PHP 函数以与 MySQL 函数相同的格式返回日期和时间NOW 我知道如何使用date 但我想问是否有专门用于此的功能 例如 返回 2009 12 01 00 00 00 您可以使用date https www php net m
  • Android GCM 服务器的 API 密钥

    我有点困惑我应该为 GCM 服务器使用哪个 API 密钥 在文档中它说使用 android api 密钥 这对我不起作用并且总是给出未经授权的 http developer android com google gcm gs html ht
  • 在 Woocommerce 购物车中设置最小小计金额

    我正在尝试将最低订单金额设置为 25 美元 到目前为止 我找到了这段代码 如果未达到最低限度 它似乎可以阻止结账 但它使用的小计包含税费 我需要在总计中排除税费 add action woocommerce checkout process
  • 如何在 HTML / Javascript 页面中插入 PHP 下拉列表

    好吧 这是我的第二篇文章 请接受我是一个完全的新手 愿意学习 花了很多时间在各个网站上寻找答案 而且我几乎已经到达了我需要到达的地方 至少在这一点上 我有一个网页 其中有许多 javascript 函数 这些函数一起使用 google 地图
  • 如何在php中使用preg添加html属性

    我正在寻找在 php 中编写一个脚本来扫描 html 文档并根据它找到的内容向元素添加新标记 更具体地说 我是扫描文档并为每个元素搜索CSS标记 float right left 如果找到它 它会添加align right left 基于它
  • 如何使用 Google 帐户对我们网站中的用户进行身份验证

    如何在我们的网站中使用 Google 帐户对用户进行身份验证 我希望用户重定向到谷歌登录页面 然后将他重定向到我的网站 我想要这个 PHP 实现 你要OAuth http code google com apis accounts docs
  • 在 PHP 中模拟 jQuery.ajax 请求

    我必须在 PHP 中模拟 AJAX 请求 就像在 jQuery 中一样 我当前的代码在这里 原始 AJAX 调用 不得修改 ajax type POST url someFile php data data success function

随机推荐