0

I am trying to implement a custom payment gateway for WooCommerce. My payment gateway provider gave me this code. When I click the place order button on the checkout page, I am getting an error on the checkout page and I am not redirect to the payment gateway provider website.

Can anyone help me to make this code compatible to WooCommerce 3.4.3 version?

**
* Load functions.
*/
add_action('plugins_loaded', 'Custom_gateway_load', 0);

function Custom_gateway_load() {

    // for USD currency add
    add_filter('woocommerce_currencies', 'Hamster_currency');

    function Hamster_currency($currencies) {
        $currencies['USD'] = __('US Dollar', 'woocommerce');
        return $currencies;
    }

    add_filter('woocommerce_currency_symbol', 'add_Hamster_currency_symbol', 10, 2);

    function add_Hamster_currency_symbol($currency_symbol, $currency) {
        switch ($currency) {
            case 'USD': $currency_symbol = 'Tk. ';
                break;
        }
        return $currency_symbol;
    }

    // starts class works
    if (!class_exists('WC_Payment_Gateway')) {
        add_action('admin_notices', 'Hamster_woocommerce_fallback_notice');
        return;
    }

    function Hamster_woocommerce_fallback_notice() {
        $html = '<div class="error">';
        $html .= '<p>WooCommerce Hamster Gateway depends on the last version of <a href="http://wordpress.org/extend/plugins/woocommerce/">WooCommerce</a> to work!</p>';
        $html .= '</div>';
        echo $html;
    }

    /**
     * Add the gateway to WooCommerce.
     *
     * @access public
     * @param array $methods
     * @return array
     */
    add_filter('woocommerce_payment_gateways', 'Hamster_add_gateway');

    function Hamster_add_gateway($methods) {
        $methods[] = 'WC_Hamster_Gateway';
        return $methods;
    }

    /* Set constant path to the hamster plugin directory. */
    define('WOO_HAMSTER_DIR', plugin_dir_path(__FILE__));
    define('WOO_HAMSTER_URL', plugin_dir_url(__FILE__));


    /**
     * WC Hamster Gateway Class.
     *
     * Built the Hamster method.
     */
    class WC_Hamster_Gateway extends WC_Payment_Gateway {

        /**
         * Gateway's Constructor.
         *
         * @return void
         */
        public function __construct() {
            global $woocommerce;
            $this->id = 'hamster';
            $this->icon = WOO_HAMSTER_URL . "images/networks.png";
            $this->has_fields = false;
            $this->order_button_text = __('Proceed to Hamster', 'woocommerce');
            $this->method_title = __('Hamster', 'woocommerce');
            $this->method_description = __('Hamster Payment Gateway', 'woocommerce');

            // 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->sandbox = $this->get_option('sandbox');

            $this->live_api_url = "https://api.hamster.com/api/v1";
            $this->live_payment_url = "https://payment.hamster.com/payment/";
            $this->sandbox_api_url = "http://api-sandbox.hamster.com/api/v1";
            $this->sandbox_payment_url = "http://payment-sandbox.hamster.com/payment/";

            // check sandbox mode or not
            if ($this->sandbox == 'yes') {
                $this->app_key = $this->get_option('sandbx_app_key');
                $this->secret_key = $this->get_option('sandbox_app_secret');
                $this->api_url = $this->sandbox_api_url;
                $this->payment_url = $this->sandbox_payment_url;
            } else {
                $this->app_key = $this->get_option('live_app_key');
                $this->secret_key = $this->get_option('live_app_secret');
                $this->api_url = $this->live_api_url;
                $this->payment_url = $this->live_payment_url;
            }



            add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        }

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

            $this->form_fields = array(
                'enabled' => array(
                    'title' => __('Enable/Disable', 'Hamster'),
                    'type' => 'checkbox',
                    'label' => __('Enable Hamster', 'Hamster'),
                    'default' => 'no'
                ),
                'title' => array(
                    'title' => __('Title', 'Hamster'),
                    'type' => 'text',
                    'description' => __('This controls the title which the user sees during checkout.', 'Hamster'),
                    'default' => __('Hamster', 'Hamster')
                ),
                'description' => array(
                    'title' => __('Description', 'Hamster'),
                    'type' => 'textarea',
                    'description' => __('This controls the description which the user sees during checkout.', 'Hamster'),
                    'default' => __('Pay with Hamster', 'Hamster')
                ),
                'sandbox' => array(
                    'title' => __('Sandbox', 'Hamster'),
                    'type' => 'checkbox',
                    'label' => __('Use sandbox environment', 'Hamster'),
                    'default' => 'yes'
                ),
                'live_app_key' => array(
                    'title' => __('Live Application Key', 'Hamster'),
                    'type' => 'text',
                    'description' => __('Please enter your Hamster Live Application Key.', 'Hamster'),
                    'default' => ''
                ),
                'live_app_secret' => array(
                    'title' => __('Live Application Secret', 'Hamster'),
                    'type' => 'text',
                    'description' => __('Please enter your Hamster Live Application Secret.', 'Hamster'),
                    'default' => ''
                ),
                'sandbx_app_key' => array(
                    'title' => __('Sandbox Application Key', 'Hamster'),
                    'type' => 'text',
                    'description' => __('Please enter your Hamster Sandbox Application Key.', 'Hamster'),
                    'default' => ''
                ),
                'sandbox_app_secret' => array(
                    'title' => __('Sandbox Application Secret', 'Hamster'),
                    'type' => 'text',
                    'description' => __('Please enter your Hamster Sandbox Application Secret.', 'Hamster'),
                    'default' => ''
                )
            );
        }

        function process_payment($order_id) {
            $order = new WC_Order($order_id);
            $hamster_args = $this->get_form_args($order);

            $params = array();
            $params['name'] = $hamster_args['payer_name'];
            $params['email'] = $hamster_args['payer_email'];
            $params['phone'] = $hamster_args['payer_phone'];
            $params['address'] = $hamster_args['payer_address'];
            $params['amount'] = $hamster_args['total'];
            $params['currency'] = $hamster_args['currency'];
            $params['ipn_url'] = add_query_arg('wc-api', 'WC_Hamster_Gateway', home_url('/'));
            $params['redirect_url'] = add_query_arg('WC_Hamster_Gateway_return', $order_id, home_url('/'));

            $params['product_name'] = 'Order #' . $order_id;
            $params['product_description'] = $hamster_args['product_description'];
            $params['order_id'] = $order_id;
            $params['zipcode'] = $hamster_args['zipcode'];
            $params['country'] = $hamster_args['country'];
            $params['city'] = $hamster_args['city'];
            $params['state'] = $hamster_args['state'];
            $gatewayInvoiceID = $this->generateInvoice($params);
            $order->add_order_note("Payment Initiated on " . date('d M Y h:i:s A') . " Hamster Invoice # " . $gatewayInvoiceID);

            return array(
                'result' => 'success',
                'redirect' => $this->payment_url . '?invoice=' . $gatewayInvoiceID
            );
        }

        /**
         * Generate the args to form.
         *
         * @param  array $order Order data.
         * @return array
         */
        public function get_form_args($order) {
            $timestamp = time();
            $order_id = $order->id;

            // get items and description
            $order_description = '';
            if (sizeof($order->get_items()) > 0) {
                foreach ($order->get_items() as $item) {
                    $order_description .= $item['qty'] . "x " . $item['name'] . " ";
                }
            }
            $order_description = trim($order_description);



            if (!empty($order->order_custom_fields['_billing_country'][0])) {
                $country = $order->order_custom_fields['_billing_country'][0];
            } else {
                $country = 'BD';
            }

            if (!empty($order->order_custom_fields['_shipping_city'][0])) {
                $city = $order->order_custom_fields['_shipping_city'][0];
            } else {
                $city = 'NA';
            }
            if (!empty($order->order_custom_fields['_shipping_state'][0])) {
                $zipcode = $order->order_custom_fields['_shipping_state'][0];
            } else {
                $zipcode = 'NA';
            }
            if (!empty($order->order_custom_fields['_shipping_city'][0])) {
                $state = $order->order_custom_fields['_shipping_city'][0];
            } else {
                $state = 'NA';
            }
            if (!empty($order->billing_last_name)) {
                $lastname = $order->billing_last_name;
            } else {
                $lastname = '';
            }



            $hamster_args = array(
                'app_key' => $this->app_key,
                'token' => md5($this->secret_key . $timestamp),
                'apiURL' => $this->api_url,
                'paymentURL' => $this->payment_url,
                'timestamp' => $timestamp,
                'currency' => get_woocommerce_currency(),
                'product_name' => 'Order ID: ' . $order->id,
                'product_description' => $order_description,
                'payer_name' => $order->billing_first_name . ' ' . $lastname,
                'payer_email' => $order->billing_email,
                'payer_phone' => $order->billing_phone,
                'payer_address' => $order->billing_address_1 . ' ' . $order->billing_address_1,
                'zipcode' => $zipcode,
                'country' => $country,
                'city' => $city,
                'state' => $state,
                'amount' => (float) $order->order_total,
                'total' => (float) $order->order_total,
                'custom' => serialize(array($order_id, $order->order_key)),
                'cancel_url' => $order->get_cancel_order_url(),
                'success_url' => esc_url($this->get_return_url($order))
            );

            return $hamster_args;
        }

        function curlRequest($url, $postParam = null) {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
            curl_setopt($ch, CURLOPT_HEADER, 0);

            if (count($postParam)) {
                curl_setopt($ch, CURLOPT_POST, TRUE);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postParam);
            }

            $result = curl_exec($ch);
            return json_decode($result);
        }

        function generateInvoice($parameters) {
            $params = array();

            $params['call'] = 'gen_invoice';

            $params['zipcode'] = $parameters['zipcode'];
            $params['country'] = $parameters['country'];
            $params['city'] = $parameters['city'];
            $params['state'] = $parameters['state'];

            $params['name'] = $parameters['name'];
            $params['email'] = $parameters['email'];
            $params['phone'] = $parameters['phone'];
            $params['address'] = $parameters['address'];
            $params['amount'] = $parameters['amount'];
            $params['currency'] = $parameters['currency'];
            $params['ipn_url'] = $parameters['ipn_url'];
            $params['redirect_url'] = $parameters['redirect_url'];
            $params['product_name'] = $parameters['product_name'];
            $params['product_description'] = $parameters['product_description'];
            $params['timestamp'] = time();
            $params['app_key'] = $this->app_key;
            $params['token'] = md5($this->secret_key . time());
            $params['order_id'] = $parameters['order_id'];

            $result = $this->curlRequest($this->api_url, $params);
            if (isset($result->status) && $result->status == 200) {
                return $result->data->invoice_id;
            } else {
                return false;
            }
        }

        function validateIPN($invoice, $amount)
        {
            $params['timestamp'] = time();
            $params['app_key'] = $this->app_key;
            $params['token'] = md5($this->secret_key . $params['timestamp']);

            $params['call'] = 'ipn_validate';
            $params['invoice'] = $invoice;
            $params['amount'] = $amount;

            $result = $this->curlRequest($this->api_url, $params);
            if (isset($result->status) && $result->status != 400) {
                return $result->data;
            } else {
                return false;
            }
        }





    }


    add_action('plugins_loaded', 'Hamster_ipn');

    function Hamster_ipn() {

        if (isset($_REQUEST['wc-api']) && $_REQUEST['wc-api'] == "WC_Hamster_Gateway") {

            if(isset($_POST) && isset($_POST['invoice']) && $_POST['amount'])
            {
                $Hamster = new WC_Hamster_Gateway();
                $data = $Hamster->validateIPN($_POST['invoice'], $_POST['amount']);
                $order = new WC_Order($data->order_id);     

                if($data->status == "ACCEPTED")
                {           
                    $order->reduce_order_stock();
                    $order->payment_complete($data->invoice_id);
                    $order->update_status("processing", "Payment Completed on " . date('d M Y h:i:s A') . " Hamster Invoice # " . $data->invoice_id);

                }elseif($data->status == "REJECTED"){
                    $order->update_status("failed", "Payment Rejected on " . date('d M Y h:i:s A') . " Hamster Invoice # " . $data->invoice_id);
                    $order->needs_payment();
                }


            }

        }
    }    

    add_action('init', 'Hamster_return');

    function Hamster_return() {


        if (isset($_REQUEST['WC_Hamster_Gateway_return']) && !empty($_REQUEST['WC_Hamster_Gateway_return'])) {

            $Hamster = new WC_Hamster_Gateway();
            $order = new WC_Order($_REQUEST['WC_Hamster_Gateway_return']);
            $hamster_args = $Hamster->get_form_args($order);

            if($order->get_status() == "processing")
            {
                $email = new WC_Emails();

                $email->emails['WC_Email_Customer_Processing_Order']->trigger($order);
                $email->emails['WC_Email_New_Order']->trigger($order);

            }

            if($_REQUEST['status'] == "ACCEPTED")
            {
                header("Location: ".html_entity_decode($hamster_args['success_url']));
                echo "<script type=\"text/javascript\">
                    <!--
                    window.location = \"".html_entity_decode($hamster_args['success_url'])."\"
                    //-->
                    </script>";
            }else{
                header("Location: ".html_entity_decode($hamster_args['cancel_url']));
                 echo "<script type=\"text/javascript\">
                    <!--
                    window.location = \"".html_entity_decode($hamster_args['cancel_url'])."\"
                    //-->
                    </script>";
            }
            die();
        }
    }    

}
0

Elsner Moneris Direct Payment Gateway for WooCommerce provides you a direct payment path without redirecting it to any other page. Except they also provide great after-sale technical support.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.