Quantcast
Channel: WordPress.org Forums » [WooCommerce] Support
Viewing all articles
Browse latest Browse all 104029

lilireed on "Payement gateways and update to woocommerce 2.0.4"

$
0
0

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: http://foro.dineromail.com/viewtopic.php?f=48&t=67
 * Description: Provides a Dineromail Standard Payment Gateway.
 * Author: dineromail, claudiosanches, lilireed
 * Author URI: http://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: http://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' );
                    }
                }
            }
        }

    }

}

Viewing all articles
Browse latest Browse all 104029

Trending Articles