Woocommerce自定义支付网关未重定向

时间:2018-11-15 09:06:53

标签: php wordpress woocommerce payment-gateway

我有一个WC付款网关,该网关已构建并可以工作到WP 4.1版。今天,我开始在WP 4.9.8和WC 3.5.1上进行测试。

当我尝试完成购买时,付款网关并未将我带到付款屏幕来填写信用卡详细信息。它停留在重定向状态。

希望有人可以帮助我解决这个问题。

在图像参考和我正在使用的代码下面:

<?php

/**
 * Plugin Name: CustomPaymentGateway
 */
add_action('plugins_loaded', 'init_mpay', 0);

function init_mpay() {

    if ( ! class_exists( 'WC_Payment_Gateway' ) ) return;

    class woocommerce_mpay extends WC_Payment_Gateway {

        public function __construct() { 
            global $woocommerce;

            $this->id           = 'mpay';
            $this->method_title = __('MPay', 'mpay-chearaan-woo');
            $this->icon         = plugins_url( 'mpay.png', __FILE__ );
            $this->has_fields   = false;
            $this->notify_url   = str_replace( 'https:', 'http:', add_query_arg( 'wc-api', 'woocommerce_mpay', home_url( '/' ) ) );

            // Load the form fields.
            $this->init_form_fields();

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

            // Define user set variables
            $this->mpayurl              = $this->settings['mpayurl'];
            $this->title                = $this->settings['title'];
            $this->description          = $this->settings['description'];
            $this->merchantid           = $this->settings['merchantid'];
            $this->hashKey              = $this->settings['hashKey'];
            $this->transactionDate      = date('Y-m-d H:i:s O');
            $this->woo_version          = $this->get_woo_version();

            // Actions
            add_action('init', array(&$this, 'successful_request'));
            add_action('woocommerce_api_woocommerce_mpay', array( &$this, 'successful_request' ));
            add_action('woocommerce_receipt_mpay', array(&$this, 'receipt_page'));
            if ( version_compare( WOOCOMMERCE_VERSION, '2.0.0', '>=' ) ) {
                add_action('woocommerce_update_options_payment_gateways_' . $this->id, array( &$this, 'process_admin_options' ));
            } else {
                add_action('woocommerce_update_options_payment_gateways', array( &$this, 'process_admin_options' ));
            }
        } 

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

            $this->form_fields = array(
                'enabled' => array(
                                'title' => __( 'Enable/Disable:', 'mpay-chearaan-woo' ), 
                                'type' => 'checkbox', 
                                'label' => __( 'Enable MPay', 'mpay-chearaan-woo' ), 
                                'default' => 'yes'
                            ), 
                'mpayurl' => array(
                                'title' => __( 'UAT/Production:', 'mpay-chearaan-woo' ), 
                                'type' => 'checkbox', 
                                'label' => __( 'UAT', 'mpay-chearaan-woo' ), 
                                'default' => 'yes'
                            ), 
                'title' => array(
                                'title' => __( 'Title:', 'mpay-chearaan-woo' ), 
                                'type' => 'text', 
                                'description' => __( 'The title which the user sees during checkout.', 'mpay-chearaan-woo' ), 
                                'default' => __( 'MPay Online Payment Gateway', 'mpay-chearaan-woo' )
                            ),
                'description' => array(
                                'title' => __( 'Description:', 'mpay-chearaan-woo' ), 
                                'type' => 'textarea', 
                                'description' => __( 'Description which the user sees during checkout.', 'mpay-chearaan-woo' ), 
                                'default' => __('Pay securely through MPay\'s Secure Servers.', 'mpay-chearaan-woo')
                            ),
                'merchantid' => array(
                                'title' => __( 'Merchant ID:', 'mpay-chearaan-woo' ), 
                                'type' => 'text', 
                                'description' => __( 'Please enter your Merchant ID as provided by MPay.', 'mpay-chearaan-woo' ), 
                                'default' => ''
                            ),
                'hashKey' => array(
                                'title' => __( 'Merchant hashKey:', 'mpay-chearaan-woo' ), 
                                'type' => 'text', 
                                'description' => __( 'Please enter your Merchant hashKey as provided by MPay.', 'mpay-chearaan-woo' ), 
                                'default' => ''
                            )
                );

        }


        public function admin_options() {
            ?>
            <h3>MPay</h3>
            <p><?php _e('MPay works by sending the user to MPay to enter their payment information.', 'mpay-chearaan-woo'); ?></p>

            <table class="form-table">
            <?php
                // Generate the HTML For the settings form.
                $this->generate_settings_html();
            ?>
            </table><!--/.form-table-->
            <?php
        } // End admin_options()

        /**
         * There are no payment fields, but we want to show the description if set.
         **/
        function payment_fields() {
            if ($this->description) echo wpautop(wptexturize($this->description));
        }

        /**
         * Generate the button link
         **/
        public function generate_mpay_form( $order_id ) {
            global $woocommerce;


            $order = new WC_Order( $order_id );

            if ($this->mpayurl == "yes"){
                $mpay_adr = "https://pcimdex.mpay.my/mdex2/payment/eCommerce";
            }else{
                $mpay_adr = "https://www.mdex.my/mdex/payment/eCommerce";
            }


            $sHash = strtoupper(hash('sha256', $this->hashKey."Continue".str_pad($this->merchantid, 10, '0', STR_PAD_LEFT).str_pad($order->id, 20, '0', STR_PAD_LEFT).str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT)));
            $mpay_args = array(
                'secureHash'        => $sHash,
                'mid'               => str_pad($this->merchantid, 10, '0', STR_PAD_LEFT),
                'invno'             => str_pad($order->id, 20, '0', STR_PAD_LEFT),
                'amt'               => str_pad(($order->order_total*100), 12, '0', STR_PAD_LEFT),
                'desc'              => str_pad("Order No ".$order_id, 255, ' ', STR_PAD_RIGHT),
                'postURL'           => $this->notify_url,
                'phone'             => $order->billing_phone,
                'email'             => $order->billing_email,
                'param'             => 'WC|V1'
            );

            $mpay_args_array = array();

            foreach ($mpay_args as $key => $value) {
                $mpay_args_array[] = '<input type="hidden" name="'.$key.'" value="'. $value .'" /><br>';
            }

            wc_enqueue_js('
                jQuery(function(){
                            jQuery("body").block(
                                { 
                                    message: "<img src=\"'.$woocommerce->plugin_url().'/images/uploading.gif\" alt=\"Redirecting…\" style=\"float:left; margin-right: 10px;\" />'.__('Thank you for your order. We are now redirecting you to MPay to make payment.', 'mpay-chearaan-woo').'", 
                                    overlayCSS: 
                                    { 
                                        background: "#fff", 
                                        opacity: 0.5 
                                    },
                                    css: { 
                                        padding:        18, 
                                        textAlign:      "center", 
                                        color:          "#555", 
                                        border:         "2px solid #aaa", 
                                        backgroundColor:"#fff", 
                                        cursor:         "wait",
                                        lineHeight:     "30px"
                                    } 
                                });
                            jQuery("#submit_mpay_payment_form").click();
                        });
            ');

        return '<form action="'.$mpay_adr.'" method="post">
                    ' . implode('', $mpay_args_array) . '
                    <input type="submit" class="button-alt" id="submit_mpay_payment_form" value="'.__('Pay via MPay', 'mpay-chearaan-woo').'" /> <a class="button cancel" href="'.$order->get_cancel_order_url().'">'.__('Cancel order &amp; restore cart', 'mpay-chearaan-woo').'</a>
                </form>';           

        }

        /**
         * Process the payment and return the result
         **/
        function process_payment( $order_id ) {

            $order = new WC_Order( $order_id );

            if($this->woo_version >= 2.1){
                $redirect = $order->get_checkout_payment_url( true );           
            }else if( $this->woo_version < 2.1 ){
                $redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
            }else{
                $redirect = add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id'))));
            }

            return array(
                'result'    => 'success',
                'redirect'  => $redirect
            );

        }

        /**
         * receipt_page
         **/
        function receipt_page( $order ) {

            echo '<p>'.__('Please click the button below to pay with MPay.', 'mpay-chearaan-woo').'</p>';

            echo $this->generate_mpay_form( $order );

        }

        /**
         * Server callback was valid, process callback (update order as passed/failed etc).
         **/
        function successful_request($mpay_response) {
            global $woocommerce;


            if (isset($_GET['wc-api']) && $_GET['wc-api'] == 'woocommerce_mpay') {
                /** need to trim from result **/
                $Url_result = $_GET['result'];
                $order = new WC_Order( (int) substr($Url_result,7,20) );
                $tranID = (int)substr($Url_result,1,6);

                if (substr($Url_result,0,1) == '0'){
                    $r_status = 0;
                }else{
                $r_status = 33;
                }

                /*
                $order = new WC_Order( (int) $_POST['invno'] );
                $r_status = (int) $_POST['result'];

                */

                if ($r_status == '0' ){

                    $order->payment_complete();

                    $order->add_order_note('MPay Payment was SUCCESSFUL '.'<br>AuthCode is '  . $tranID);

                    wp_redirect( $this->get_return_url($order) ); exit;
                    //wp_redirect( $this->order->get_checkout_order_received_url() ); exit;

                }else{

                    $order->update_status('failed', sprintf(__('MPay Payment Failed. Error Communicating with Bank.', 'mpay-chearaan-woo') ) );

                    wp_redirect($order->get_cancel_order_url()); exit;

                }
            }               
        }

        function get_woo_version() {

            // If get_plugins() isn't available, require it
            if ( ! function_exists( 'get_plugins' ) )
                require_once( ABSPATH . 'wp-admin/includes/plugin.php' );

            // Create the plugins folder and file variables
            $plugin_folder = get_plugins( '/woocommerce' );
            $plugin_file = 'woocommerce.php';

            // If the plugin version number is set, return it 
            if ( isset( $plugin_folder[$plugin_file]['Version'] ) ) {
                return $plugin_folder[$plugin_file]['Version'];

            } else {
                // Otherwise return null
                return NULL;
            }
        }
    }
}

/**
 * Add the gateway to WooCommerce
 **/
function add_mpay( $methods ) {
    $methods[] = 'woocommerce_mpay'; return $methods;
}

add_filter('woocommerce_payment_gateways', 'add_mpay' );

enter image description here

0 个答案:

没有答案