• Resolved lilireed

    (@lilireed)


    Hi, I had some code that I added to the plugin to add DineroMail as a gateway. It worked fine before the last version of woocommerce came up, when I updated the fix no longer worked. What I would like to know is if anyone knows what changed in the last woocommerce version (2.0.4) that I should have to change in the code I have.

    I’ll copy it below so you can see.
    First the gateway had to be added to woocommerce.php by adding
    include( 'classes/gateways/dineromail/class-wc-dineromail.php' );

    Second the DineroMail icon had to be added to the icons folder and finally in the classes folder add a file named class-wc-dineromail.php that contained:

    <?php
    /**
     * DineroMail Standard Payment Gateway
     *
     * Provides a Dineromail Standard Payment Gateway.
     *
     * @class 		WC_Dineromail
     * @extends		WC_Payment_Gateway
     */
    class WC_Dineromail extends WC_Payment_Gateway {
    
        /**
         * Constructor for the gateway.
         *
         * @access public
         * @return void
         */
    	public function __construct() {
    		global $woocommerce;
    
            $this->id			= 'dineromail';
            $this->icon 		= apply_filters('woocommerce_dineromail_icon', $woocommerce->plugin_url() . '/assets/images/icons/dineromail.png');
            $this->has_fields 	= false;
            $this->liveurl 		= 'https://checkout.dineromail.com/CheckOut';
    		$this->testurl 		= 'https://checkout.dineromail.com/CheckOut';
            $this->method_title = __( 'DineroMail', 'woocommerce' );
    
    		// Load the form fields.
    		$this->init_form_fields();
    
    		// Load the settings.
    		$this->init_settings();
    
    		// Define user set variables
    		$this->title 			= $this->settings['title'];
    		$this->description 		= $this->settings['description'];
            $this->cuenta    = $this->settings['cuenta'];
    		$this->email 			= $this->settings['email'];
            $this->country    = $this->settings['country'];
            $this->logo    = $this->settings['logo'];
            $this->ipnpass    = $this->settings['ipnpass'];
    		$this->form_submission_method = ( isset( $this->settings['form_submission_method'] ) && $this->settings['form_submission_method'] == 'yes' ) ? true : false;
    		// Logs
    		$this->log = $woocommerce->logger();
    
    		// Actions
    		add_action( 'init', array(&$this, 'check_ipn_response') );
    		add_action('valid-dineromail-standard-ipn-request', array(&$this, 'successful_request') );
    		add_action('woocommerce_receipt_dineromail', array(&$this, 'receipt_page'));
    		add_action('woocommerce_update_options_payment_gateways', array(&$this, 'process_admin_options'));
    
    		if ( !$this->is_valid_for_use() ) $this->enabled = false;
        }
    
        function is_valid_for_use() {
            if (!in_array(get_woocommerce_currency(), array('ARS', 'BRL', 'CLP', 'MXN', 'USD'))) return false;
    
            return true;
        }
    
    	public function admin_options() {
    
        	?>
        	<h3><?php _e('DineroMail standard', 'woocommerce'); ?></h3>
        	<p><?php _e('DineroMail standard works by sending the user to DineroMail to enter their payment information.', 'woocommerce'); ?></p>
        	<table class="form-table">
        	<?php
        		if ( $this->is_valid_for_use() ) :
    
        			// Generate the HTML For the settings form.
        			$this->generate_settings_html();
    
        		else :
    
        			?>
                		<div class="inline error"><p><strong><?php _e( 'Gateway Disabled', 'woocommerce' ); ?></strong>: <?php _e( 'DineroMail does not support your store currency.', 'woocommerce' ); ?></p></div>
            		<?php
    
        		endif;
        	?>
    		</table><!--/.form-table-->
        	<?php
        }
    
        function init_form_fields() {
    
        	$this->form_fields = array(
    			'enabled' => array(
    							'title' => __( 'Activar/Desactivar', 'woocommerce' ),
    							'type' => 'checkbox',
    							'label' => __( 'Activar DineroMail Estándar', 'woocommerce' ),
    							'default' => 'yes'
    						),
    			'title' => array(
    							'title' => __( 'Title', 'woocommerce' ),
    							'type' => 'text',
    							'description' => __( '<br />Este el título que el usuario mira en el checkout de WordPress.', 'woocommerce' ),
    							'default' => __( 'DineroMail', 'woocommerce' )
    						),
    			'description' => array(
    							'title' => __( 'Description', 'woocommerce' ),
    							'type' => 'textarea',
    							'description' => __( 'Esta és la descripción que el usuario mira en el checkout de WordPress.', 'woocommerce' ),
    							'default' => __("Pago con DineroMail", 'woocommerce')
    						),
    			'cuenta' => array(
    							'title' => __( 'Número de la Cuenta', 'woocommerce' ),
    							'type' => 'text',
    							'description' => __( '<br />Debe ser insertado sin la barra(/) y sin el último dígito.', 'woocommerce' ),
    							'default' => ''
    						),
                'email' => array(
                                'title' => __( 'Mail de Registro en DineroMail', 'woocommerce' ),
                                'type' => 'text',
                                'description' => __( '<br />Informe el mail que usou para se registrar en DineroMail.', 'woocommerce' ),
                                'default' => ''
                            ),
                'country' => array(
                                'title' => __( 'País de Registro', 'woocommerce' ),
                                'type' => 'select',
                                'description' => __( '<br />Informe el país de registro de su cuenta de DineroMail.', 'woocommerce' ),
                                'options' => array(
                                    'Argentina' => __( 'Argentina', 'woocommerce' ),
                                    'Brasil' => __( 'Brasil', 'woocommerce' ),
                                    'Chile' => __( 'Chile', 'woocommerce' ),
                                    'México' => __( 'México', 'woocommerce' )
                                )
                            ),
    
                'logo' => array(
                                'title' => __( 'Logo de la Tienda', 'woocommerce' ),
                                'type' => 'text',
                                'description' => __( '<br />Informe la url donde está alojada la imagen. Ejemplo: https://www.meusite/imagens/logo.jpg<br />Tama?o máximo que debes tener <b>756x100</b>.', 'woocommerce' ),
                                'default' => '',
                                'readyonli'
                            ),
                'ipnpass' => array(
                                'title' => __( 'Contrase?a IPN', 'woocommerce' ),
                                'type' => 'text',
                                'description' => __( '<br />Informe la contrase?a IPN caso vás usar la notificación de DienroMail.<br />Use la URL informada abajo para configurar la Notificación de DineroMail.<br />Para más informaciones sobre la IPN, consulte el manual IPN disponible en la url <a href="https://br.dineromail.com/biblioteca" target="_blank">https://br.dineromail.com/biblioteca</a>.', 'woocommerce' ),
                                'default' => ''
                            ),
                'ipnurl' => array(
                                'title' => __( 'URL IPN', 'woocommerce' ),
                                'type' => 'textarea',
                                'description' => __( 'Caso vás usar la notificacion de DineroMail use la url ariba.<br />Para más informaciones sobre la URL IPN consulte el Manual IPN disponible en la url <a href="https://br.dineromail.com/biblioteca" target="_blank">https://br.dineromail.com/biblioteca</a>', 'woocommerce' ),
                                'default' => trailingslashit( home_url() ) . '?dineromailListener=dineromail_standard_IPN'
                            )
    			);
    
        }
    
    	function get_dineromail_args( $order ) {
    		global $woocommerce;
    
    		$order_id = $order->id;
    
            if($this->country == "Argentina") {
                $currency = "ars";
                $language = "es";
                $countryid = 1;
            }
            elseif($this->country == "Brasil") {
                $currency = "brl";
                $language = "pt";
                $countryid = 2;
            }
            elseif($this->country == "Chile") {
                $currency = "clp";
                $language = "es";
                $countryid = 3;
            }
            elseif($this->country == "México") {
                $currency = "mxn";
                $language = "es";
                $countryid = 4;
            }
    
    		if ($this->debug=='yes') $this->log->add( 'dineromail', 'Generating payment form for order #' . $order_id . '. Notify URL: ' . trailingslashit(home_url()).'?dineromailListener=dineromail_standard_IPN');
    
    		$dineromail_args = array_merge(
    			array(
    				'change_quantity' => '0',
    				'payment_method_available' => 'all',
    				'merchant' 		  => $this->cuenta,
    				'country_id' 	  => $countryid,
    				'header_image' 	  => $this->logo,
    				'seller_name' 	  => get_bloginfo( 'name' ),
    				'language' 		  => $language,
    				'transaction_id'  => $order_id,
    				'currency'        => $currency,
    				'ok_url'          => add_query_arg( 'utm_nooverride', '1', $this->get_return_url( $order ) ),
    				'pending_url' 	  => add_query_arg( 'utm_nooverride', '1', $this->get_return_url( $order ) ),
    				'error_url'		  => $order->get_cancel_order_url(),
    
    				// Billing Address info
    				'buyer_name'	  => $order->billing_first_name,
    				'buyer_lastname'  => $order->billing_last_name,
    				'buyer_email'     => $order->billing_email,
    				'buyer_phone'	  => str_replace( array( '(', '-', ' ', ')', '.' ), '', $order->billing_phone )
    
    			)
    		);
    
    		// If prices include tax or have order discounts, send the whole order as a single item
    		if ( get_option('woocommerce_prices_include_tax')=='yes' || $order->get_order_discount() > 0 ) :
                $pricediscount = sprintf('%.1f',$order->get_order_discount());
    			// Discount
    			$dineromail_args['display_additional_charge'] = 1;
                $dineromail_args['additional_fixed_charge'] = $pricediscount.'-';
    			$dineromail_args['additional_fixed_charge_currency'] = get_woocommerce_currency();
            endif;    
    
    		$item_names = array();
    
    		if (sizeof($order->get_items())>0) : foreach ($order->get_items() as $item) :
                if ($item['qty']) :
    
                    $item_loop++;
    
                    $product = $order->get_product_from_item($item);
    
                    $item_name  = $item['name'];
    
                    $item_meta = new WC_Order_Item_Meta( $item['item_meta'] );
                    if ($meta = $item_meta->display( true, true )) :
                        $item_name .= ' ('.$meta.')';
                    endif;
    
                    $dineromail_args['item_name_'.$item_loop] = $item_name;
                    $dineromail_args['item_quantity_'.$item_loop] = $item['qty'];
                    $dineromail_args['item_ammount_'.$item_loop] = $order->get_item_total( $item, false );//$order->get_item_total( $item, true, true );
                    $dineromail_args['item_currency_'.$item_loop] = get_woocommerce_currency();
    
                endif;
            endforeach; endif;
    			// Shipping Cost
    
    		if ( ( $order->get_shipping() + $order->get_shipping_tax() ) > 0 ) :
                $item_loop++;
    			$dineromail_args['item_name_'.$item_loop] ='WPW - Tasa de Flete';
    			$dineromail_args['item_quantity_'.$item_loop] 	= '1';
    			$dineromail_args['item_ammount_'.$item_loop] 	= number_format( $order->get_shipping(), 2, '.', '' );//number_format( $order->get_shipping() + $order->get_shipping_tax() , 2, '.', '' );
                $dineromail_args['item_currency_'.$item_loop] = get_woocommerce_currency();
    		endif;
    
            if ( $order->get_total_tax() > 0 ) :
                $item_loop++;
                $dineromail_args['item_name_'.$item_loop] ='WPW - Tasa de Impuesto';
                $dineromail_args['item_quantity_'.$item_loop]  = '1';
                $dineromail_args['item_ammount_'.$item_loop]    = number_format( $order->get_total_tax() , 2, '.', '' );
                $dineromail_args['item_currency_'.$item_loop] = get_woocommerce_currency();
            endif;
    
    		$dineromail_args = apply_filters( 'woocommerce_dineromail_args', $dineromail_args );
    
    		return $dineromail_args;
    	}
    
        function generate_dineromail_form( $order_id ) {
    		global $woocommerce;
    
    		$order = new WC_Order( $order_id );
    
            $dineromail_adr = $this->liveurl;
    
    		$dineromail_args = $this->get_dineromail_args( $order );
    
    		$dineromail_args_array = array();
    
    		foreach ($dineromail_args as $key => $value) {
    			$dineromail_args_array[] = '<input type="hidden" name="'.esc_attr( $key ).'" value="'.esc_attr( $value ).'" />';
    		}
    
    		$woocommerce->add_inline_js('
    			jQuery("body").block({
    					message: "<img src=\"' . esc_url( apply_filters( 'woocommerce_ajax_loader_url', $woocommerce->plugin_url() . '/assets/images/ajax-loader.gif' ) ) . '\" alt=\"Redirecting…\" style=\"float:left; margin-right: 10px;\" />'.__('Gracias por su pedido. Ahora estamos te redirigiremos a DineroMail para hacer el pago.', 'woocommerce').'",
    					overlayCSS:
    					{
    						background: "#fff",
    						opacity: 0.6
    					},
    					css: {
    				        padding:        28,
    				        textAlign:      "center",
    				        color:          "#555",
    				        border:         "3px solid #aaa",
    				        backgroundColor:"#fff",
    				        cursor:         "wait",
    				        lineHeight:		"32px"
    				    }
    				});
    			jQuery("#submit_dineromail_payment_form").click();
    		');
    
    		return '<form action="'.esc_url( $dineromail_adr ).'" method="post" id="dineromail_payment_form" target="_top">
    				' . implode('', $dineromail_args_array) . '
    				<input type="submit" class="button-alt" id="submit_dineromail_payment_form" value="'.__('Pay via DineroMail', 'woocommerce').'" /> <a class="button cancel" href="'.esc_url( $order->get_cancel_order_url() ).'">'.__('Cancel order & restore cart', 'woocommerce').'</a>
    			</form>';
    
    	}
    
    	function process_payment( $order_id ) {
    
    		$order = new WC_Order( $order_id );
    
    		if ( $this->form_submission_method ) {
    
    			$dineromail_args = $this->get_dineromail_args( $order );
    
    			$dineromail_args = http_build_query( $dineromail_args, '', '&' );
    
    			$dineromail_adr = $this->liveurl . '?';
    
    			return array(
    				'result' 	=> 'success',
    				'redirect'	=> $dineromail_adr . $dineromail_args
    			);
    
    		} else {
    
    			return array(
    				'result' 	=> 'success',
    				'redirect'	=> add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(woocommerce_get_page_id('pay'))))
    			);
    
    		}
    
    	}
    
    	function receipt_page( $order ) {
    
    		echo '<p>'.__('Thank you for your order, please click the button below to pay with DineroMail.', 'woocommerce').'</p>';
    
    		echo $this->generate_dineromail_form( $order );
    
    	}
    
    	/**
    	 * Check DineroMail IPN validity
    	 **/
    	function check_ipn_request_is_valid() {
    		global $woocommerce;
    
    		if ($this->debug=='yes') $this->log->add( 'dineromail', 'Checking IPN response is valid...' );
    
        	// Get recieved values from post data
    		$received_values = (array) stripslashes_deep( $_POST );
    
    		 // Add cmd to the post array
    		$received_values['cmd'] = '_notify-validate';
    
            // Send back post vars to dineromail
            $params = array(
            	'body' 			=> $received_values,
            	'sslverify' 	=> false,
            	'timeout' 		=> 30,
            	'user-agent'	=> 'WooCommerce/' . $woocommerce->version
            );
    
            // Get url
           	if ( $this->testmode == 'yes' ):
    			$dineromail_adr = $this->testurl;
    		else :
    			$dineromail_adr = $this->liveurl;
    		endif;
    
    		// Post back to get a response
            $response = wp_remote_post( $dineromail_adr, $params );
    
            if ($this->debug=='yes') $this->log->add( 'dineromail', 'IPN Response: ' . print_r($response, true) );
    
            // check to see if the request was valid
            if ( !is_wp_error($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300 && (strcmp( $response['body'], "VERIFIED") == 0)) {
                if ($this->debug=='yes') $this->log->add( 'dineromail', 'Received valid response from DineroMail' );
                return true;
            }
    
            if ($this->debug=='yes') :
            	$this->log->add( 'dineromail', 'Received invalid response from DineroMail' );
            	if (is_wp_error($response)) :
            		$this->log->add( 'dineromail', 'Error response: ' . $result->get_error_message() );
            	endif;
            endif;
    
            return false;
        }
    
    	/**
    	 * Check for DineroMail IPN Response
    	 *
    	 * @access public
    	 * @return void
    	 */
    	function check_ipn_response() {
    
    		if (isset($_GET['dineromailListener']) && $_GET['dineromailListener'] == 'dineromail_standard_IPN'):
    
            	$_POST = stripslashes_deep($_POST);
                if($_REQUEST['Notificacion']){          
    
                    ini_set("allow_url_fopen", 1);
                    ini_set("allow_url_include", 1);            
    
                    $notificacion = htmlspecialchars_decode($_REQUEST['Notificacion']);
                    $notificacion = str_replace("<?xml version='1.0'encoding='ISO-8859-1'?>", "", $notificacion);
                    $notificacion = str_replace("<?xml version=\'1.0\'encoding=\'ISO-8859-1\'?>", "", $notificacion);
                    $notificacion = str_replace("<?xmlversion=\'1.0\'encoding=\'ISO-8859-1\'?>", "", $notificacion);
                    $notificacion = str_replace("<?xmlversion='1.0'encoding='ISO-8859-1'?>", "", $notificacion);
                    $notificacion = str_replace("<?xml version='1.0' encoding='ISO-8859-1'?>", "", $notificacion);
                    $notificacion = str_replace("<?xml version=\'1.0\' encoding=\'ISO-8859-1\'?>", "", $notificacion);
    
                    $doc = new SimpleXMLElement($notificacion);
                    $tipo_notificacion = $doc ->tiponotificacion;
                    foreach ($doc ->operaciones ->operacion  as  $OPERACION){
                        $id_operacion = $OPERACION->id;
                        $this->successful_request($id_operacion);
                    }
                }
    
           	endif;
    	}
    
    	/**
    	 * Successful Payment!
    	 *
    	 * @access public
    	 * @param array $posted
    	 * @return void
    	 */
    	function successful_request( $id_operacion ) {
    
            global $woocommerce;
    
            $order = new WC_Order( (int)$id_operacion );      
    
            $nrocta = $this->cuenta;
            $senhaipn = $this->ipnpass;
            //var_dump($order);
            if($this->country == "Argentina") {
                 $url="https://argentina.dineromail.com/Vender/Consulta_IPN.asp";
            }
            elseif($this->country == "Brasil") {
                $url="https://brasil.dineromail.com/Vender/Consulta_IPN.asp";
            }
            elseif($this->country == "Chile") {
                $url="https://chile.dineromail.com/Vender/Consulta_IPN.asp";
            }
            elseif($this->country == "México") {
                $url="https://mexico.dineromail.com/Vender/Consulta_IPN.asp";
            }
    
            $data = 'DATA=<REPORTE><NROCTA>'.$nrocta.'</NROCTA><DETALLE><CONSULTA><CLAVE>'.$senhaipn.'</CLAVE><TIPO>1</TIPO><OPERACIONES><ID>'.$id_operacion.'</ID></OPERACIONES></CONSULTA></DETALLE></REPORTE>';
    
            $url = parse_url($url);
            $host = $url['host'];
            $path = $url['path'];
            $fp = fsockopen($host, 80);
            fputs($fp, "POST $path HTTP/1.1\r\n");
            fputs($fp, "Host: $host\r\n");
            //fputs($fp, "Referer: $referer\r\n");
            fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
            fputs($fp, "Content-length: ". strlen($data) ."\r\n");
            fputs($fp, "Connection: close\r\n\r\n");
            fputs($fp, $data);
            $result = ''; 
    
            while(!feof($fp)) {
                // resultado del request
                $result .= fgets($fp, 128);
            }
            // cierra conexion
            fclose($fp);
            // separa el header del content
            $result = explode("\r\n\r\n", $result, 2);
            //$header = isset($result[0]) ? $result[0] : '';
            $content = isset($result[1]) ? $result[1] : '';  
    
            $xml = new SimpleXMLElement($content);
            $estadoxml = $xml ->ESTADOREPORTE;
    
            if($estadoxml==1){
    
                foreach ($xml ->DETALLE->OPERACIONES->OPERACION  as  $OPERACION){
    
                    $trx_id= $OPERACION->ID;
                    $estadotrans= $OPERACION->ESTADO; 
    
                    if($estadotrans==1){
                       $order->update_status( 'pending' );
                    }
                    elseif($estadotrans==2){
                       $order->update_status( 'completed' );
                    }
                    elseif($estadotrans==3){
                       $order->update_status( 'cancelled' );
                    }
                }
            }
        }
    
    }
    
    /**
     * Add the gateway to WooCommerce
     *
     * @access public
     * @param array $methods
     * @package		WooCommerce/Classes/Payment
     * @return array
     */
    function add_dineromail_gateway( $methods ) {
    	$methods[] = 'WC_Dineromail';
    	return $methods;
    }
    
    add_filter('woocommerce_payment_gateways', 'add_dineromail_gateway' );

    if anyone understands spanish the whole explanation is here

    Could anyone help me out here?

    Thanks so much.

    Lili

    https://www.ads-software.com/extend/plugins/woocommerce/

Viewing 15 replies - 1 through 15 (of 28 total)
  • edit this code:

    function is_valid_for_use() {
    if (!in_array(get_woocommerce_currency(), array(‘ARS’, ‘BRL’, ‘CLP’, ‘MXN’, ‘USD’))) return false;

    return true;
    }

    you have to add your currency code to the array of currencies
    find out your currentcy by echoing result from get_woocommerce_currency() and add it to array

    It should work!

    I had the same problem with Croatian kuna

    Thread Starter lilireed

    (@lilireed)

    thanks kbilicicweb!

    I had my currency added to woocommerce with a plugin so that should’ve been working…
    Anyway, Claudio from https://claudiosmweb.com/ helped me tons and made a working plugin out of that code that so far has had no glitches.
    If anyone is interested in the results let me know and I’ll send you the files.

    cheers!

    Hello lilireed,

    I’m interested in the files, you can send them to me?
    Gracias!

    cgutierrezv[@]gmail.com

    Hello lilireed,

    I’m also interested in the files you got from claudio, you can send them to me?
    Gracias!

    [email address moderated – these forums do not provide support via email]

    lilireed, can you send me those files?
    Thanks in advance.
    ngonchan[at]gmail dot com.

    hola lilireed, puedes pegar aquí esos códigos así los vemos todos?

    Gracias!!!

    Thread Starter lilireed

    (@lilireed)

    Hola Cristian,
    Te lo adjunto aquí pero también necesitas una carpeta asociada con el logo de Dineromail. Si quieres usar este código agrega una carpeta llamada “images” que tenga un archivo dineromail.jpg de 48x48px.

    <?php
    /**
     * Plugin Name: Woocommerce DineroMail Gateway
     * Plugin URI: https://foro.dineromail.com/viewtopic.php?f=48&t=67
     * Description: Provides a Dineromail Standard Payment Gateway.
     * Author: dineromail, claudiosanches, lilireed
     * Author URI: https://foro.dineromail.com/
     * Version: 0.1
     */
    
    /**
     * Load functions.
     */
    add_action( 'plugins_loaded', 'wcdinheiromail_gateway_load', 0 );
    
    function wcdinheiromail_gateway_load() {
    
        /**
         * Add the gateway to WooCommerce
         *
         * @access public
         * @param array $methods
         * @package     WooCommerce/Classes/Payment
         * @return array
         */
        function add_dineromail_gateway( $methods ) {
            $methods[] = 'WC_Dineromail';
            return $methods;
        }
    
        add_filter( 'woocommerce_payment_gateways', 'add_dineromail_gateway' );
    
        /**
         * DineroMail Standard Payment Gateway
         *
         * Provides a Dineromail Standard Payment Gateway.
         *
         * @class 		WC_Dineromail
         * @extends		WC_Payment_Gateway
         */
        class WC_Dineromail extends WC_Payment_Gateway {
    
            /**
             * Constructor for the gateway.
             *
             * @access public
             * @return void
             */
        	public function __construct() {
        		global $woocommerce;
    
                $this->id			= 'dineromail';
                $this->icon 		= plugins_url( 'images/dineromail.jpg', __FILE__ );
                $this->has_fields 	= false;
                $this->liveurl 		= 'https://checkout.dineromail.com/CheckOut';
        		$this->testurl 		= 'https://checkout.dineromail.com/CheckOut';
                $this->method_title = __( 'DineroMail', 'woocommerce' );
    
        		// Load the form fields.
        		$this->init_form_fields();
    
        		// Load the settings.
        		$this->init_settings();
    
        		// Define user set variables
        		$this->title 			= $this->settings['title'];
        		$this->description 		= $this->settings['description'];
                $this->cuenta    = $this->settings['cuenta'];
        		$this->email 			= $this->settings['email'];
                $this->country    = $this->settings['country'];
                $this->logo    = $this->settings['logo'];
                $this->ipnpass    = $this->settings['ipnpass'];
        		$this->form_submission_method = ( isset( $this->settings['form_submission_method'] ) && $this->settings['form_submission_method'] == 'yes' ) ? true : false;
        		// Logs
        		$this->log = $woocommerce->logger();
    
        		// Actions
        		add_action( 'init', array(&$this, 'check_ipn_response') );
        		add_action('valid-dineromail-standard-ipn-request', array(&$this, 'successful_request') );
        		add_action('woocommerce_receipt_dineromail', 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' ) );
                }
    
        		if ( !$this->is_valid_for_use() ) $this->enabled = false;
            }
    
            function is_valid_for_use() {
                if (!in_array(get_woocommerce_currency(), array('ARS', 'BRL', 'CLP', 'MXN', 'USD'))) return false;
    
                return true;
            }
    
        	public function admin_options() {
    
            	?>
            	<h3><?php _e('DineroMail standard', 'woocommerce'); ?></h3>
            	<p><?php _e('DineroMail standard works by sending the user to DineroMail to enter their payment information.', 'woocommerce'); ?></p>
            	<table class="form-table">
            	<?php
            		if ( $this->is_valid_for_use() ) :
    
            			// Generate the HTML For the settings form.
            			$this->generate_settings_html();
    
            		else :
    
            			?>
                    		<div class="inline error"><p><strong><?php _e( 'Gateway Disabled', 'woocommerce' ); ?></strong>: <?php _e( 'DineroMail does not support your store currency.', 'woocommerce' ); ?></p></div>
                		<?php
    
            		endif;
            	?>
        		</table><!--/.form-table-->
            	<?php
            }
    
            function init_form_fields() {
    
            	$this->form_fields = array(
        			'enabled' => array(
        							'title' => __( 'Activar/Desactivar', 'woocommerce' ),
        							'type' => 'checkbox',
        							'label' => __( 'Activar DineroMail Estándar', 'woocommerce' ),
        							'default' => 'yes'
        						),
        			'title' => array(
        							'title' => __( 'Title', 'woocommerce' ),
        							'type' => 'text',
        							'description' => __( '<br />Este el título que el usuario mira en el checkout de WordPress.', 'woocommerce' ),
        							'default' => __( 'DineroMail', 'woocommerce' )
        						),
        			'description' => array(
        							'title' => __( 'Description', 'woocommerce' ),
        							'type' => 'textarea',
        							'description' => __( 'Esta es la descripción que el usuario mira en el checkout de WordPress.', 'woocommerce' ),
        							'default' => __("Pago con DineroMail", 'woocommerce')
        						),
        			'cuenta' => array(
        							'title' => __( 'Número de la Cuenta', 'woocommerce' ),
        							'type' => 'text',
        							'description' => __( '<br />Debe ser insertado sin la barra(/) y sin el último dígito.', 'woocommerce' ),
        							'default' => ''
        						),
                    'email' => array(
                                    'title' => __( 'Mail de Registro en DineroMail', 'woocommerce' ),
                                    'type' => 'text',
                                    'description' => __( '<br />Informe el mail que uso para se registrar en DineroMail.', 'woocommerce' ),
                                    'default' => ''
                                ),
                    'country' => array(
                                    'title' => __( 'País de Registro', 'woocommerce' ),
                                    'type' => 'select',
                                    'description' => __( '<br />Informe el país de registro de su cuenta de DineroMail.', 'woocommerce' ),
                                    'options' => array(
                                        'Argentina' => __( 'Argentina', 'woocommerce' ),
                                        'Brasil' => __( 'Brasil', 'woocommerce' ),
                                        'Chile' => __( 'Chile', 'woocommerce' ),
                                        'México' => __( 'México', 'woocommerce' )
                                    )
                                ),
    
                    'logo' => array(
                                    'title' => __( 'Logo de la Tienda', 'woocommerce' ),
                                    'type' => 'text',
                                    'description' => __( '<br />Informe la url donde está alojada la imagen. Ejemplo: https://www.meusite/imagens/logo.jpg<br />Tama&ntilde;o m&aacute;ximo: <b>756x100</b>.', 'woocommerce' ),
                                    'default' => '',
                                    'readyonli'
                                ),
                    'ipnpass' => array(
                                    'title' => __( 'Contrase?a IPN', 'woocommerce' ),
                                    'type' => 'text',
                                    'description' => __( '<br />Informe la contrase?a IPN caso v&aacute;s usar la notificación de DineroMail.<br />Use la URL informada abajo para configurar la Notificación de DineroMail.<br />Para más informaciones sobre la IPN, consulte el manual IPN disponible en la url <a href="https://br.dineromail.com/biblioteca" target="_blank">https://br.dineromail.com/biblioteca</a>.', 'woocommerce' ),
                                    'default' => ''
                                ),
                    'ipnurl' => array(
                                    'title' => __( 'URL IPN', 'woocommerce' ),
                                    'type' => 'textarea',
                                    'description' => __( 'Caso v&aacute;s usar la notificacion de DineroMail use la url ariba.<br />Para más información sobre la URL IPN consulte el Manual IPN disponible en la url <a href="https://br.dineromail.com/biblioteca" target="_blank">https://br.dineromail.com/biblioteca</a>', 'woocommerce' ),
                                    'default' => trailingslashit( home_url() ) . '?dineromailListener=dineromail_standard_IPN'
                                )
        			);
    
            }
    
        	function get_dineromail_args( $order ) {
        		global $woocommerce;
    
        		$order_id = $order->id;
    
                if($this->country == "Argentina") {
                    $currency = "ars";
                    $language = "es";
                    $countryid = 1;
                }
                elseif($this->country == "Brasil") {
                    $currency = "brl";
                    $language = "pt";
                    $countryid = 2;
                }
                elseif($this->country == "Chile") {
                    $currency = "clp";
                    $language = "es";
                    $countryid = 3;
                }
                elseif($this->country == "México") {
                    $currency = "mxn";
                    $language = "es";
                    $countryid = 4;
                }
    
        		if ($this->debug=='yes') $this->log->add( 'dineromail', 'Generating payment form for order #' . $order_id . '. Notify URL: ' . trailingslashit(home_url()).'?dineromailListener=dineromail_standard_IPN');
    
        		$dineromail_args = array_merge(
        			array(
        				'change_quantity' => '0',
        				'payment_method_available' => 'all',
        				'merchant' 		  => $this->cuenta,
        				'country_id' 	  => $countryid,
        				'header_image' 	  => $this->logo,
        				'seller_name' 	  => get_bloginfo( 'name' ),
        				'language' 		  => $language,
        				'transaction_id'  => $order_id,
        				'currency'        => $currency,
        				'ok_url'          => add_query_arg( 'utm_nooverride', '1', $this->get_return_url( $order ) ),
        				'pending_url' 	  => add_query_arg( 'utm_nooverride', '1', $this->get_return_url( $order ) ),
        				'error_url'		  => $order->get_cancel_order_url(),
    
        				// Billing Address info
        				'buyer_name'	  => $order->billing_first_name,
        				'buyer_lastname'  => $order->billing_last_name,
        				'buyer_email'     => $order->billing_email,
        				'buyer_phone'	  => str_replace( array( '(', '-', ' ', ')', '.' ), '', $order->billing_phone )
    
        			)
        		);
    
        		// If prices include tax or have order discounts, send the whole order as a single item
        		if ( get_option('woocommerce_prices_include_tax')=='yes' || $order->get_order_discount() > 0 ) :
                    $pricediscount = sprintf('%.1f',$order->get_order_discount());
        			// Discount
        			$dineromail_args['display_additional_charge'] = 1;
                    $dineromail_args['additional_fixed_charge'] = $pricediscount.'-';
        			$dineromail_args['additional_fixed_charge_currency'] = get_woocommerce_currency();
                endif;
    
        		$item_names = array();
    
        		if (sizeof($order->get_items())>0) : foreach ($order->get_items() as $item) :
                    if ($item['qty']) :
    
                        $item_loop++;
    
                        $product = $order->get_product_from_item($item);
    
                        $item_name  = $item['name'];
    
                        $item_meta = new WC_Order_Item_Meta( $item['item_meta'] );
                        if ($meta = $item_meta->display( true, true )) :
                            $item_name .= ' ('.$meta.')';
                        endif;
    
                        $dineromail_args['item_name_'.$item_loop] = $item_name;
                        $dineromail_args['item_quantity_'.$item_loop] = $item['qty'];
                        $dineromail_args['item_ammount_'.$item_loop] = $order->get_item_total( $item, false );//$order->get_item_total( $item, true, true );
                        $dineromail_args['item_currency_'.$item_loop] = get_woocommerce_currency();
    
                    endif;
                endforeach; endif;
        			// Shipping Cost
    
        		if ( ( $order->get_shipping() + $order->get_shipping_tax() ) > 0 ) :
                    $item_loop++;
        			$dineromail_args['item_name_'.$item_loop] ='WPW - Tasa de Flete';
        			$dineromail_args['item_quantity_'.$item_loop] 	= '1';
        			$dineromail_args['item_ammount_'.$item_loop] 	= number_format( $order->get_shipping(), 2, '.', '' );//number_format( $order->get_shipping() + $order->get_shipping_tax() , 2, '.', '' );
                    $dineromail_args['item_currency_'.$item_loop] = get_woocommerce_currency();
        		endif;
    
                if ( $order->get_total_tax() > 0 ) :
                    $item_loop++;
                    $dineromail_args['item_name_'.$item_loop] ='WPW - Tasa de Impuesto';
                    $dineromail_args['item_quantity_'.$item_loop]  = '1';
                    $dineromail_args['item_ammount_'.$item_loop]    = number_format( $order->get_total_tax() , 2, '.', '' );
                    $dineromail_args['item_currency_'.$item_loop] = get_woocommerce_currency();
                endif;
    
        		$dineromail_args = apply_filters( 'woocommerce_dineromail_args', $dineromail_args );
    
        		return $dineromail_args;
        	}
    
            function generate_dineromail_form( $order_id ) {
        		global $woocommerce;
    
        		$order = new WC_Order( $order_id );
    
                $dineromail_adr = $this->liveurl;
    
        		$dineromail_args = $this->get_dineromail_args( $order );
    
        		$dineromail_args_array = array();
    
        		foreach ($dineromail_args as $key => $value) {
        			$dineromail_args_array[] = '<input type="hidden" name="'.esc_attr( $key ).'" value="'.esc_attr( $value ).'" />';
        		}
    
        		$woocommerce->add_inline_js('
        			jQuery("body").block({
        					message: "<img src=\"' . esc_url( apply_filters( 'woocommerce_ajax_loader_url', $woocommerce->plugin_url() . '/assets/images/ajax-loader.gif' ) ) . '\" alt=\"Redirecting&hellip;\" style=\"float:left; margin-right: 10px;\" />'.__('Gracias por su pedido. Ahora estamos te redirigiremos a DineroMail para hacer el pago.', 'woocommerce').'",
        					overlayCSS:
        					{
        						background: "#fff",
        						opacity: 0.6
        					},
        					css: {
        				        padding:        28,
        				        textAlign:      "center",
        				        color:          "#555",
        				        border:         "3px solid #aaa",
        				        backgroundColor:"#fff",
        				        cursor:         "wait",
        				        lineHeight:		"32px"
        				    }
        				});
        			jQuery("#submit_dineromail_payment_form").click();
        		');
    
        		return '<form action="'.esc_url( $dineromail_adr ).'" method="post" id="dineromail_payment_form" target="_top">
        				' . implode('', $dineromail_args_array) . '
        				<input type="submit" class="button-alt" id="submit_dineromail_payment_form" value="'.__('Pay via DineroMail', 'woocommerce').'" /> <a class="button cancel" href="'.esc_url( $order->get_cancel_order_url() ).'">'.__('Cancel order & restore cart', 'woocommerce').'</a>
        			</form>';
    
        	}
    
        	function process_payment( $order_id ) {
    
        		$order = new WC_Order( $order_id );
    
        		if ( $this->form_submission_method ) {
    
        			$dineromail_args = $this->get_dineromail_args( $order );
    
        			$dineromail_args = http_build_query( $dineromail_args, '', '&' );
    
        			$dineromail_adr = $this->liveurl . '?';
    
        			return array(
        				'result' 	=> 'success',
        				'redirect'	=> $dineromail_adr . $dineromail_args
        			);
    
        		} else {
    
        			return array(
        				'result' 	=> 'success',
        				'redirect'	=> add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(woocommerce_get_page_id('pay'))))
        			);
    
        		}
    
        	}
    
        	function receipt_page( $order ) {
    
        		echo '<p>'.__('Thank you for your order, please click the button below to pay with DineroMail.', 'woocommerce').'</p>';
    
        		echo $this->generate_dineromail_form( $order );
    
        	}
    
        	/**
        	 * Check DineroMail IPN validity
        	 **/
        	function check_ipn_request_is_valid() {
        		global $woocommerce;
    
        		if ($this->debug=='yes') $this->log->add( 'dineromail', 'Checking IPN response is valid...' );
    
            	// Get recieved values from post data
        		$received_values = (array) stripslashes_deep( $_POST );
    
        		 // Add cmd to the post array
        		$received_values['cmd'] = '_notify-validate';
    
                // Send back post vars to dineromail
                $params = array(
                	'body' 			=> $received_values,
                	'sslverify' 	=> false,
                	'timeout' 		=> 30,
                	'user-agent'	=> 'WooCommerce/' . $woocommerce->version
                );
    
                // Get url
               	if ( $this->testmode == 'yes' ):
        			$dineromail_adr = $this->testurl;
        		else :
        			$dineromail_adr = $this->liveurl;
        		endif;
    
        		// Post back to get a response
                $response = wp_remote_post( $dineromail_adr, $params );
    
                if ($this->debug=='yes') $this->log->add( 'dineromail', 'IPN Response: ' . print_r($response, true) );
    
                // check to see if the request was valid
                if ( !is_wp_error($response) && $response['response']['code'] >= 200 && $response['response']['code'] < 300 && (strcmp( $response['body'], "VERIFIED") == 0)) {
                    if ($this->debug=='yes') $this->log->add( 'dineromail', 'Received valid response from DineroMail' );
                    return true;
                }
    
                if ($this->debug=='yes') :
                	$this->log->add( 'dineromail', 'Received invalid response from DineroMail' );
                	if (is_wp_error($response)) :
                		$this->log->add( 'dineromail', 'Error response: ' . $result->get_error_message() );
                	endif;
                endif;
    
                return false;
            }
    
        	/**
        	 * Check for DineroMail IPN Response
        	 *
        	 * @access public
        	 * @return void
        	 */
        	function check_ipn_response() {
    
        		if (isset($_GET['dineromailListener']) && $_GET['dineromailListener'] == 'dineromail_standard_IPN'):
    
                	$_POST = stripslashes_deep($_POST);
                    if($_REQUEST['Notificacion']){
    
                        ini_set("allow_url_fopen", 1);
                        ini_set("allow_url_include", 1);
    
                        $notificacion = htmlspecialchars_decode($_REQUEST['Notificacion']);
                        $notificacion = str_replace("<?xml version='1.0'encoding='ISO-8859-1'?>", "", $notificacion);
                        $notificacion = str_replace("<?xml version=\'1.0\'encoding=\'ISO-8859-1\'?>", "", $notificacion);
                        $notificacion = str_replace("<?xmlversion=\'1.0\'encoding=\'ISO-8859-1\'?>", "", $notificacion);
                        $notificacion = str_replace("<?xmlversion='1.0'encoding='ISO-8859-1'?>", "", $notificacion);
                        $notificacion = str_replace("<?xml version='1.0' encoding='ISO-8859-1'?>", "", $notificacion);
                        $notificacion = str_replace("<?xml version=\'1.0\' encoding=\'ISO-8859-1\'?>", "", $notificacion);
    
                        $doc = new SimpleXMLElement($notificacion);
                        $tipo_notificacion = $doc ->tiponotificacion;
                        foreach ($doc ->operaciones ->operacion  as  $OPERACION){
                            $id_operacion = $OPERACION->id;
                            $this->successful_request($id_operacion);
                        }
                    }
    
               	endif;
        	}
    
        	/**
        	 * Successful Payment!
        	 *
        	 * @access public
        	 * @param array $posted
        	 * @return void
        	 */
        	function successful_request( $id_operacion ) {
    
                global $woocommerce;
    
                $order = new WC_Order( (int)$id_operacion );
    
                $nrocta = $this->cuenta;
                $senhaipn = $this->ipnpass;
                //var_dump($order);
                if($this->country == "Argentina") {
                     $url="https://argentina.dineromail.com/Vender/Consulta_IPN.asp";
                }
                elseif($this->country == "Brasil") {
                    $url="https://brasil.dineromail.com/Vender/Consulta_IPN.asp";
                }
                elseif($this->country == "Chile") {
                    $url="https://chile.dineromail.com/Vender/Consulta_IPN.asp";
                }
                elseif($this->country == "México") {
                    $url="https://mexico.dineromail.com/Vender/Consulta_IPN.asp";
                }
    
                $data = 'DATA=<REPORTE><NROCTA>'.$nrocta.'</NROCTA><DETALLE><CONSULTA><CLAVE>'.$senhaipn.'</CLAVE><TIPO>1</TIPO><OPERACIONES><ID>'.$id_operacion.'</ID></OPERACIONES></CONSULTA></DETALLE></REPORTE>';
    
                $url = parse_url($url);
                $host = $url['host'];
                $path = $url['path'];
                $fp = fsockopen($host, 80);
                fputs($fp, "POST $path HTTP/1.1\r\n");
                fputs($fp, "Host: $host\r\n");
                //fputs($fp, "Referer: $referer\r\n");
                fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
                fputs($fp, "Content-length: ". strlen($data) ."\r\n");
                fputs($fp, "Connection: close\r\n\r\n");
                fputs($fp, $data);
                $result = '';
    
                while(!feof($fp)) {
                    // resultado del request
                    $result .= fgets($fp, 128);
                }
                // cierra conexion
                fclose($fp);
                // separa el header del content
                $result = explode("\r\n\r\n", $result, 2);
                //$header = isset($result[0]) ? $result[0] : '';
                $content = isset($result[1]) ? $result[1] : '';
    
                $xml = new SimpleXMLElement($content);
                $estadoxml = $xml ->ESTADOREPORTE;
    
                if($estadoxml==1){
    
                    foreach ($xml ->DETALLE->OPERACIONES->OPERACION  as  $OPERACION){
    
                        $trx_id= $OPERACION->ID;
                        $estadotrans= $OPERACION->ESTADO;
    
                        if($estadotrans==1){
                           $order->update_status( 'pending' );
                        }
                        elseif($estadotrans==2){
                           $order->update_status( 'completed' );
                        }
                        elseif($estadotrans==3){
                           $order->update_status( 'cancelled' );
                        }
                    }
                }
            }
    
        }
    
    }

    ?En qué línea o dentro de qué función haces la llamada en woocommerce.php?

    include( 'classes/gateways/dineromail/class-wc-dineromail.php' );

    These are English language forums, so please use English. Alternatively, use a WP support forum in your language.

    Oh sorry. So, the question is: Where do I have to put this line into woocommerce.php?

    include( 'classes/gateways/dineromail/class-wc-dineromail.php' );

    Thread Starter lilireed

    (@lilireed)

    You don’t have to, this plugin includes the gateway without having to modify the woocommerce code. You have to make a plugin folder called wc-dineromail, with a file inside called wc-dineromail.php that has the code I pasted in it, and a folder called images with the dineromail.jpg file i mentioned before, 48x48px.

    Thanks a lot. It worked fine for me.

    Hi lilireed! Thanks for sharing this!

    Its seems to be working perfect!!!

    But i have one question. I would like to give users the possibility to pay with dineromail or with paypal…. but i would like to show the prices in my woocommerce site always in ARS….

    How can I achieve this?

    Because i have added the Woocommerce Ars currency plugin from Claudio Sanchez… but it seems that paypal dont accept “pesos”…. Any hint?

    Thanks!!!

    Thread Starter lilireed

    (@lilireed)

    Hi juampolo,
    I think that this is a problem with Paypal. As far as I understand Paypal doesn’t operate in Argentine Pesos. Before, they would convert pesos to dollars for you and this conversion allowed you to pay in “pesos” (or their equivalent, converted to dollars). Unfortunately, since some time in 1012 this conversion from pesos to dollars has been suspended, so payments in pesos are no longer available. Check it out, I may be wrong.
    Cheers

    Hey Juampolo, I’m going to save you, a lot of time, with this answer… there is no way to pay with ARS with Paypal.

    There is a option, but implies that, you have to hire a programmer to make a specific plugin for you. A plugin that allows the convertion of the amount in Ars to Usd, but it is dificult.
    Otherwise, you can create a mirror webpage to put all the products in USD with links in to there in your ARS page, to redirect the clients who wants to pay in Paypal. It is the easiest solution I find, until today.

Viewing 15 replies - 1 through 15 (of 28 total)
  • The topic ‘Payement gateways and update to woocommerce 2.0.4’ is closed to new replies.