/**
  * Process the payment and return the result
  *
  * @access public
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     global $woocommerce;
     $this->init_mijireh();
     $mj_order = new Mijireh_Order();
     $wc_order = new WC_Order($order_id);
     // add items to order
     $items = $wc_order->get_items();
     foreach ($items as $item) {
         $product = $wc_order->get_product_from_item($item);
         $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item), $item['qty'], $product->get_sku());
     }
     // add billing address to order
     $billing = new Mijireh_Address();
     $billing->first_name = $wc_order->billing_first_name;
     $billing->last_name = $wc_order->billing_last_name;
     $billing->street = $wc_order->billing_address_1;
     $billing->apt_suite = $wc_order->billing_address_2;
     $billing->city = $wc_order->billing_city;
     $billing->state_province = $wc_order->billing_state;
     $billing->zip_code = $wc_order->billing_postcode;
     $billing->country = $wc_order->billing_country;
     $billing->company = $wc_order->billing_company;
     $billing->phone = $wc_order->billing_phone;
     if ($billing->validate()) {
         $mj_order->set_billing_address($billing);
     }
     // add shipping address to order
     $shipping = new Mijireh_Address();
     $shipping->first_name = $wc_order->shipping_first_name;
     $shipping->last_name = $wc_order->shipping_last_name;
     $shipping->street = $wc_order->shipping_address_1;
     $shipping->apt_suite = $wc_order->shipping_address_2;
     $shipping->city = $wc_order->shipping_city;
     $shipping->state_province = $wc_order->shipping_state;
     $shipping->zip_code = $wc_order->shipping_postcode;
     $shipping->country = $wc_order->shipping_country;
     $shipping->company = $wc_order->shipping_company;
     if ($shipping->validate()) {
         $mj_order->set_shipping_address($shipping);
     }
     // set order name
     $mj_order->first_name = $wc_order->billing_first_name;
     $mj_order->last_name = $wc_order->billing_last_name;
     $mj_order->email = $wc_order->billing_email;
     // set order totals
     $mj_order->total = $wc_order->get_order_total();
     $mj_order->tax = $wc_order->get_total_tax();
     $mj_order->discount = $wc_order->get_total_discount();
     $mj_order->shipping = $wc_order->get_shipping();
     // add meta data to identify woocommerce order
     $mj_order->add_meta_data('wc_order_id', $order_id);
     // Set URL for mijireh payment notificatoin - use WC API
     $mj_order->return_url = str_replace('https:', 'http:', add_query_arg('wc-api', 'WC_Mijireh_Checkout', home_url('/')));
     // Identify woocommerce
     $mj_order->partner_id = 'woo';
     try {
         $mj_order->create();
         $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url);
         return $result;
     } catch (Mijireh_Exception $e) {
         $woocommerce->add_error(__('Mijireh error:', 'woocommerce') . $e->getMessage());
     }
 }
 /**
  * Charge Payment
  * Method ini digunakan untuk mendapatkan link halaman pembayaran Veritrans
  * dengan mengirimkan JSON yang berisi data transaksi
  */
 function charge_payment($order_id)
 {
     global $woocommerce;
     $order_items = array();
     $cart = $woocommerce->cart;
     $order = new WC_Order($order_id);
     // add discount
     // WC()->cart->add_discount( 'veritrans' );
     $cart->add_discount('veritrans');
     $order->add_coupon('veritrans', WC()->cart->get_coupon_discount_amount('veritrans'), WC()->cart->get_coupon_discount_tax_amount('veritrans'));
     $order->set_total(WC()->cart->shipping_total, 'shipping');
     $order->set_total(WC()->cart->get_cart_discount_total(), 'cart_discount');
     $order->set_total(WC()->cart->get_cart_discount_tax_total(), 'cart_discount_tax');
     $order->set_total(WC()->cart->tax_total, 'tax');
     $order->set_total(WC()->cart->shipping_tax_total, 'shipping_tax');
     $order->set_total(WC()->cart->total);
     // $order->add_coupon('veritrans',10000);
     // end of add discount
     Veritrans_Config::$isProduction = $this->environment == 'production' ? true : false;
     Veritrans_Config::$serverKey = Veritrans_Config::$isProduction ? $this->server_key_v2_production : $this->server_key_v2_sandbox;
     Veritrans_Config::$is3ds = true;
     Veritrans_Config::$isSanitized = $this->enable_sanitization == 'yes' ? true : false;
     $params = array('transaction_details' => array('order_id' => $order_id, 'gross_amount' => 0), 'vtweb' => array());
     $enabled_payments = array();
     // if ($this->enable_credit_card == 'yes'){
     //   $enabled_payments[] = 'credit_card';
     // }
     // check enabled payment
     if ($this->enable_credit_card == 'yes') {
         $params['vtweb']['enabled_payments'] = 'credit_card';
     }
     if ($this->enable_permata_va == 'yes') {
         $params['vtweb']['enabled_payments'] = 'bank_transfer';
     }
     // add bin filter
     $bins = $this->bin_filter;
     $bins = explode(',', $bins);
     $params['vtweb']['credit_card_bins'] = $bins;
     $customer_details = array();
     $customer_details['first_name'] = $order->billing_first_name;
     $customer_details['last_name'] = $order->billing_last_name;
     $customer_details['email'] = $order->billing_email;
     $customer_details['phone'] = $order->billing_phone;
     $billing_address = array();
     $billing_address['first_name'] = $order->billing_first_name;
     $billing_address['last_name'] = $order->billing_last_name;
     $billing_address['address'] = $order->billing_address_1;
     $billing_address['city'] = $order->billing_city;
     $billing_address['postal_code'] = $order->billing_postcode;
     $billing_address['phone'] = $order->billing_phone;
     $billing_address['country_code'] = strlen($this->convert_country_code($order->billing_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
     $customer_details['billing_address'] = $billing_address;
     $customer_details['shipping_address'] = $billing_address;
     if (isset($_POST['ship_to_different_address'])) {
         $shipping_address = array();
         $shipping_address['first_name'] = $order->shipping_first_name;
         $shipping_address['last_name'] = $order->shipping_last_name;
         $shipping_address['address'] = $order->shipping_address_1;
         $shipping_address['city'] = $order->shipping_city;
         $shipping_address['postal_code'] = $order->shipping_postcode;
         $shipping_address['phone'] = $order->billing_phone;
         $shipping_address['country_code'] = strlen($this->convert_country_code($order->shipping_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
         $customer_details['shipping_address'] = $shipping_address;
     }
     $params['customer_details'] = $customer_details;
     //error_log(print_r($params,true));
     $items = array();
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if ($item['qty']) {
                 $product = $order->get_product_from_item($item);
                 $veritrans_item = array();
                 $veritrans_item['id'] = $item['product_id'];
                 $veritrans_item['price'] = $order->get_item_subtotal($item, false);
                 $veritrans_item['quantity'] = $item['qty'];
                 $veritrans_item['name'] = $item['name'];
                 $items[] = $veritrans_item;
             }
         }
     }
     // Shipping fee
     if ($order->get_total_shipping() > 0) {
         $items[] = array('id' => 'shippingfee', 'price' => $order->get_total_shipping(), 'quantity' => 1, 'name' => 'Shipping Fee');
     }
     // Tax
     if ($order->get_total_tax() > 0) {
         $items[] = array('id' => 'taxfee', 'price' => $order->get_total_tax(), 'quantity' => 1, 'name' => 'Tax');
     }
     // Discount
     if ($order->get_cart_discount() > 0) {
         $items[] = array('id' => 'totaldiscount', 'price' => $order->get_cart_discount() * -1, 'quantity' => 1, 'name' => 'Total Discount');
     }
     // Fees
     if (sizeof($order->get_fees()) > 0) {
         $fees = $order->get_fees();
         $i = 0;
         foreach ($fees as $item) {
             $items[] = array('id' => 'itemfee' . $i, 'price' => $item['line_total'], 'quantity' => 1, 'name' => $item['name']);
             $i++;
         }
     }
     //calculate gross amount
     $total_amount = 0;
     // error_log('print r items[]' . print_r($items,true)); //debugan
     foreach ($items as $item) {
         $total_amount += $item['price'] * $item['quantity'];
         // error_log('|||| Per item[]' . print_r($item,true)); //debugan
     }
     $params['transaction_details']['gross_amount'] = $total_amount;
     // error_log('bni'.$this->enable_bni);
     // error_log('mandiri'.$this->enable_mandiri);
     // if($this->enable_bni == 'yes' || $this->enable_mandiri == 'yes')
     if (false) {
         $installment_terms = array();
         $payment_options = array('installment' => array('required' => true, 'installment_terms' => new stdClass(), 'offline_installment_terms' => array()));
         // $term_bni = $this->bni_terms;
         // error_log('term bni '.$term_bni);
         // $term_bni_array = explode(',' , $term_bni);
         // if($term_bni == "yes" || $term_bni_array != null)
         // {
         //   $installment_terms['bni'] = $term_bni_array;
         // }
         // $term_mandiri =  $this->mandiri_terms;
         // error_log('term mandiri '.$term_mandiri);
         // $term_mandiri_array = explode(',' , $term_mandiri);
         // if($term_mandiri == "yes" || $term_mandiri_array != null)
         // {
         //   $installment_terms['mandiri'] = $term_mandiri_array;
         // }
         $term = $this->installment_terms;
         error_log('============installment_terms ' . $term);
         $term_array = explode(',', $term);
     }
     // sift through the entire item to ensure that currency conversion is applied
     if (get_woocommerce_currency() != 'IDR') {
         foreach ($items as &$item) {
             $item['price'] = $item['price'] * $this->to_idr_rate;
         }
         unset($item);
         $params['transaction_details']['gross_amount'] *= $this->to_idr_rate;
     }
     $params['item_details'] = $items;
     // if($params['transaction_details']['gross_amount'] >= $this->min_amount)
     // {
     //   $payment_options['installment']['offline_installment_terms'] = $term_array;
     //   $params['vtweb']['payment_options'] = $payment_options;
     // }
     $woocommerce->cart->empty_cart();
     error_log(print_r($params, TRUE));
     // error_log(json_encode($params));
     return Veritrans_VtWeb::getRedirectionUrl($params);
 }
 /**
  * Process the payment and return the result
  *
  * @access public
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $this->init_mijireh();
     $mj_order = new Mijireh_Order();
     $wc_order = new WC_Order($order_id);
     // Avoid rounding issues altogether by sending the order as one lump
     if (get_option('woocommerce_prices_include_tax') == 'yes') {
         // Don't pass items - Pass 1 item for the order items overall
         $item_names = array();
         if (sizeof($wc_order->get_items()) > 0) {
             foreach ($wc_order->get_items() as $item) {
                 if ($item['qty']) {
                     $item_names[] = $item['name'] . ' x ' . $item['qty'];
                 }
             }
         }
         $mj_order->add_item(sprintf(__('Order %s', 'woocommerce'), $wc_order->get_order_number()) . " - " . implode(', ', $item_names), number_format($wc_order->get_total() - round($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2) + $wc_order->get_order_discount(), 2, '.', ''), 1);
         if ($wc_order->get_total_shipping() + $wc_order->get_shipping_tax() > 0) {
             $mj_order->shipping = number_format($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2, '.', '');
         }
         $mj_order->show_tax = false;
         // No issues when prices exclude tax
     } else {
         // add items to order
         $items = $wc_order->get_items();
         foreach ($items as $item) {
             $product = $wc_order->get_product_from_item($item);
             $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, false, true), $item['qty'], $product->get_sku());
         }
         // Handle fees
         $items = $wc_order->get_fees();
         foreach ($items as $item) {
             $mj_order->add_item($item['name'], number_format($item['line_total'], 2, '.', ','), 1, '');
         }
         $mj_order->shipping = round($wc_order->get_total_shipping(), 2);
         $mj_order->tax = $wc_order->get_total_tax();
     }
     // set order totals
     $mj_order->total = $wc_order->get_total();
     $mj_order->discount = $wc_order->get_total_discount();
     // add billing address to order
     $billing = new Mijireh_Address();
     $billing->first_name = $wc_order->billing_first_name;
     $billing->last_name = $wc_order->billing_last_name;
     $billing->street = $wc_order->billing_address_1;
     $billing->apt_suite = $wc_order->billing_address_2;
     $billing->city = $wc_order->billing_city;
     $billing->state_province = $wc_order->billing_state;
     $billing->zip_code = $wc_order->billing_postcode;
     $billing->country = $wc_order->billing_country;
     $billing->company = $wc_order->billing_company;
     $billing->phone = $wc_order->billing_phone;
     if ($billing->validate()) {
         $mj_order->set_billing_address($billing);
     }
     // add shipping address to order
     $shipping = new Mijireh_Address();
     $shipping->first_name = $wc_order->shipping_first_name;
     $shipping->last_name = $wc_order->shipping_last_name;
     $shipping->street = $wc_order->shipping_address_1;
     $shipping->apt_suite = $wc_order->shipping_address_2;
     $shipping->city = $wc_order->shipping_city;
     $shipping->state_province = $wc_order->shipping_state;
     $shipping->zip_code = $wc_order->shipping_postcode;
     $shipping->country = $wc_order->shipping_country;
     $shipping->company = $wc_order->shipping_company;
     if ($shipping->validate()) {
         $mj_order->set_shipping_address($shipping);
     }
     // set order name
     $mj_order->first_name = $wc_order->billing_first_name;
     $mj_order->last_name = $wc_order->billing_last_name;
     $mj_order->email = $wc_order->billing_email;
     // add meta data to identify woocommerce order
     $mj_order->add_meta_data('wc_order_id', $order_id);
     // Set URL for mijireh payment notificatoin - use WC API
     $mj_order->return_url = WC()->api_request_url('WC_Gateway_Mijireh');
     // Identify woocommerce
     $mj_order->partner_id = 'woo';
     try {
         $mj_order->create();
         $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url);
         return $result;
     } catch (Mijireh_Exception $e) {
         wc_add_notice(__('Mijireh error:', 'woocommerce') . $e->getMessage() . print_r($mj_order, true), 'error');
     }
 }
 /**
  * Get line items to send to paypal
  *
  * @param  WC_Order $order
  * @return array on success, or false when it is not possible to send line items
  */
 private function get_line_items($order)
 {
     // Do not send lines for tax inclusive prices
     if ('yes' === get_option('woocommerce_calc_taxes') && 'yes' === get_option('woocommerce_prices_include_tax')) {
         return false;
     }
     // Do not send lines when order discount is present, or too many line items in the order.
     if ($order->get_order_discount() > 0 || sizeof($order->get_items()) + sizeof($order->get_fees()) >= 9) {
         return false;
     }
     $item_loop = 0;
     $args = array();
     $args['tax_cart'] = $order->get_total_tax();
     // Products
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if (!$item['qty']) {
                 continue;
             }
             $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 . ' )';
             }
             $args['item_name_' . $item_loop] = $this->paypal_item_name($item_name);
             $args['quantity_' . $item_loop] = $item['qty'];
             $args['amount_' . $item_loop] = $order->get_item_subtotal($item, false);
             if ($args['amount_' . $item_loop] < 0) {
                 return false;
                 // Abort - negative line
             }
             if ($product->get_sku()) {
                 $args['item_number_' . $item_loop] = $product->get_sku();
             }
         }
     }
     // Discount
     if ($order->get_cart_discount() > 0) {
         $args['discount_amount_cart'] = round($order->get_cart_discount(), 2);
     }
     // Fees
     if (sizeof($order->get_fees()) > 0) {
         foreach ($order->get_fees() as $item) {
             $item_loop++;
             $args['item_name_' . $item_loop] = $this->paypal_item_name($item['name']);
             $args['quantity_' . $item_loop] = 1;
             $args['amount_' . $item_loop] = $item['line_total'];
             if ($args['amount_' . $item_loop] < 0) {
                 return false;
                 // Abort - negative line
             }
         }
     }
     // Shipping Cost item - paypal only allows shipping per item, we want to send shipping for the order
     if ($order->get_total_shipping() > 0) {
         $item_loop++;
         $args['item_name_' . $item_loop] = $this->paypal_item_name(sprintf(__('Shipping via %s', 'woocommerce'), $order->get_shipping_method()));
         $args['quantity_' . $item_loop] = '1';
         $args['amount_' . $item_loop] = number_format($order->get_total_shipping(), 2, '.', '');
     }
     return $args;
 }
 /**
  * Charge Payment
  * Method ini digunakan untuk mendapatkan link halaman pembayaran Veritrans
  * dengan mengirimkan JSON yang berisi data transaksi
  */
 function charge_payment($order_id)
 {
     global $woocommerce;
     $order_items = array();
     $cart = $woocommerce->cart;
     $order = new WC_Order($order_id);
     Veritrans_Config::$isProduction = $this->environment == 'production' ? true : false;
     Veritrans_Config::$serverKey = Veritrans_Config::$isProduction ? $this->server_key_v2_production : $this->server_key_v2_sandbox;
     Veritrans_Config::$is3ds = $this->enable_3d_secure == 'yes' ? true : false;
     Veritrans_Config::$isSanitized = $this->enable_sanitization == 'yes' ? true : false;
     $params = array('transaction_details' => array('order_id' => $order_id, 'gross_amount' => 0), 'vtweb' => array());
     $enabled_payments = array();
     if ($this->enable_credit_card == 'yes') {
         $enabled_payments[] = 'credit_card';
     }
     if ($this->enable_mandiri_clickpay == 'yes') {
         $enabled_payments[] = 'mandiri_clickpay';
     }
     if ($this->enable_cimb_clicks == 'yes') {
         $enabled_payments[] = 'cimb_clicks';
     }
     if ($this->enable_permata_va == 'yes') {
         $enabled_payments[] = 'bank_transfer';
     }
     if ($this->enable_bri_epay == 'yes') {
         $enabled_payments[] = 'bri_epay';
     }
     if ($this->enable_telkomsel_cash == 'yes') {
         $enabled_payments[] = 'telkomsel_cash';
     }
     if ($this->enable_xl_tunai == 'yes') {
         $enabled_payments[] = 'xl_tunai';
     }
     if ($this->enable_mandiri_bill == 'yes') {
         $enabled_payments[] = 'echannel';
     }
     if ($this->enable_bbmmoney == 'yes') {
         $enabled_payments[] = 'bbm_money';
     }
     if ($this->enable_indomaret == 'yes') {
         $enabled_payments[] = 'cstore';
     }
     if ($this->enable_indosat_dompetku == 'yes') {
         $enabled_payments[] = 'indosat_dompetku';
     }
     if ($this->enable_mandiri_ecash == 'yes') {
         $enabled_payments[] = 'mandiri_ecash';
     }
     $params['vtweb']['enabled_payments'] = $enabled_payments;
     $customer_details = array();
     $customer_details['first_name'] = $order->billing_first_name;
     $customer_details['last_name'] = $order->billing_last_name;
     $customer_details['email'] = $order->billing_email;
     $customer_details['phone'] = $order->billing_phone;
     $billing_address = array();
     $billing_address['first_name'] = $order->billing_first_name;
     $billing_address['last_name'] = $order->billing_last_name;
     $billing_address['address'] = $order->billing_address_1;
     $billing_address['city'] = $order->billing_city;
     $billing_address['postal_code'] = $order->billing_postcode;
     $billing_address['phone'] = $order->billing_phone;
     $billing_address['country_code'] = strlen($this->convert_country_code($order->billing_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
     $customer_details['billing_address'] = $billing_address;
     $customer_details['shipping_address'] = $billing_address;
     if (isset($_POST['ship_to_different_address'])) {
         $shipping_address = array();
         $shipping_address['first_name'] = $order->shipping_first_name;
         $shipping_address['last_name'] = $order->shipping_last_name;
         $shipping_address['address'] = $order->shipping_address_1;
         $shipping_address['city'] = $order->shipping_city;
         $shipping_address['postal_code'] = $order->shipping_postcode;
         $shipping_address['phone'] = $order->billing_phone;
         $shipping_address['country_code'] = strlen($this->convert_country_code($order->shipping_country) != 3) ? 'IDN' : $this->convert_country_code($order->billing_country);
         $customer_details['shipping_address'] = $shipping_address;
     }
     $params['customer_details'] = $customer_details;
     //error_log(print_r($params,true));
     $items = array();
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if ($item['qty']) {
                 $product = $order->get_product_from_item($item);
                 $veritrans_item = array();
                 $veritrans_item['id'] = $item['product_id'];
                 $veritrans_item['price'] = $order->get_item_subtotal($item, false);
                 $veritrans_item['quantity'] = $item['qty'];
                 $veritrans_item['name'] = $item['name'];
                 $items[] = $veritrans_item;
             }
         }
     }
     // Shipping fee
     if ($order->get_total_shipping() > 0) {
         $items[] = array('id' => 'shippingfee', 'price' => $order->get_total_shipping(), 'quantity' => 1, 'name' => 'Shipping Fee');
     }
     // Tax
     if ($order->get_total_tax() > 0) {
         $items[] = array('id' => 'taxfee', 'price' => $order->get_total_tax(), 'quantity' => 1, 'name' => 'Tax');
     }
     // Discount
     if ($cart->get_cart_discount_total() > 0) {
         $items[] = array('id' => 'totaldiscount', 'price' => $cart->get_cart_discount_total() * -1, 'quantity' => 1, 'name' => 'Total Discount');
     }
     // Fees
     if (sizeof($order->get_fees()) > 0) {
         $fees = $order->get_fees();
         $i = 0;
         foreach ($fees as $item) {
             $items[] = array('id' => 'itemfee' . $i, 'price' => $item['line_total'], 'quantity' => 1, 'name' => $item['name']);
             $i++;
         }
     }
     $total_amount = 0;
     // error_log('print r items[]' . print_r($items,true)); //debugan
     foreach ($items as $item) {
         $total_amount += $item['price'] * $item['quantity'];
         // error_log('|||| Per item[]' . print_r($item,true)); //debugan
     }
     error_log('order get total = ' . $order->get_total());
     error_log('total amount = ' . $total_amount);
     $params['transaction_details']['gross_amount'] = $total_amount;
     // sift through the entire item to ensure that currency conversion is applied
     if (get_woocommerce_currency() != 'IDR') {
         foreach ($items as &$item) {
             $item['price'] = $item['price'] * $this->to_idr_rate;
         }
         unset($item);
         $params['transaction_details']['gross_amount'] *= $this->to_idr_rate;
     }
     $params['item_details'] = $items;
     $woocommerce->cart->empty_cart();
     return Veritrans_VtWeb::getRedirectionUrl($params);
 }
 /**
  * Set up the DoExpressCheckoutPayment request
  *
  * @link https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECGettingStarted/#id084RN060BPF
  * @link https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoExpressCheckoutPayment_API_Operation_NVP/
  *
  * @since 3.0.0
  * @param \WC_Order $order order object
  * @param string $type
  */
 private function do_payment(WC_Order $order, $type)
 {
     $this->set_method('DoExpressCheckoutPayment');
     // set base params
     $this->add_parameters(array('TOKEN' => $order->paypal_express_token, 'PAYERID' => !empty($order->paypal_express_payer_id) ? $order->paypal_express_payer_id : null, 'BUTTONSOURCE' => 'WooThemes_Cart', 'RETURNFMFDETAILS' => 1));
     $order_subtotal = $i = 0;
     $order_items = array();
     // add line items
     foreach ($order->get_items() as $item) {
         $product = new WC_Product($item['product_id']);
         $order_items[] = array('NAME' => SV_WC_Helper::str_truncate(html_entity_decode($product->get_title(), ENT_QUOTES, 'UTF-8'), 127), 'DESC' => $this->get_item_description($item, $product), 'AMT' => $order->get_item_subtotal($item), 'QTY' => !empty($item['qty']) ? absint($item['qty']) : 1, 'ITEMURL' => $product->get_permalink());
         $order_subtotal += $item['line_total'];
     }
     // add fees
     foreach ($order->get_fees() as $fee) {
         $order_items[] = array('NAME' => SV_WC_Helper::str_truncate($fee['name'], 127), 'AMT' => $fee['line_total'], 'QTY' => 1);
         $order_subtotal += $fee['line_total'];
     }
     if (SV_WC_Plugin_Compatibility::is_wc_version_gte_2_3()) {
         // WC 2.3+, no after-tax discounts
         if ($order->get_total_discount() > 0) {
             $order_items[] = array('NAME' => __('Total Discount', WC_Paypal_Express::TEXT_DOMAIN), 'QTY' => 1, 'AMT' => -$order->get_total_discount());
         }
     } else {
         // WC 2.2 or lesser
         // add cart discounts as line item
         if ($order->get_cart_discount() > 0) {
             $order_items[] = array('NAME' => __('Cart Discount', WC_Paypal_Express::TEXT_DOMAIN), 'QTY' => 1, 'AMT' => -$order->get_cart_discount());
         }
         // add order discounts as line item
         if ($order->get_order_discount() > 0) {
             $order_items[] = array('NAME' => __('Order Discount', WC_Paypal_Express::TEXT_DOMAIN), 'QTY' => 1, 'AMT' => -$order->get_order_discount());
         }
     }
     $total_discount = SV_WC_Plugin_Compatibility::is_wc_version_gte_2_3() ? 0 : $order->get_order_discount();
     // order subtotal includes pre-tax discounts in 2.3
     if ($this->skip_line_items($order)) {
         $item_names = array();
         foreach ($order_items as $item) {
             $item_names[] = sprintf('%s x %s', $item['NAME'], $item['QTY']);
         }
         // add a single item for the entire order
         $this->add_line_item_parameters(array('NAME' => sprintf(__('%s - Order', WC_PayPal_Express::TEXT_DOMAIN), get_option('blogname')), 'DESC' => SV_WC_Helper::str_truncate(html_entity_decode(implode(', ', $item_names), ENT_QUOTES, 'UTF-8'), 127), 'AMT' => $order_subtotal - $total_discount + $order->get_cart_tax(), 'QTY' => 1), 0);
         // add order-level parameters
         //  - Do not sent the TAXAMT due to rounding errors
         $this->add_payment_parameters(array('AMT' => $order->get_total(), 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $order_subtotal - $total_discount + $order->get_cart_tax(), 'SHIPPINGAMT' => $order->get_total_shipping() + $order->get_shipping_tax(), 'INVNUM' => $order->paypal_express_invoice_prefix . SV_WC_Helper::str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number', WC_PayPal_Express::TEXT_DOMAIN))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id));
     } else {
         // add individual order items
         foreach ($order_items as $item) {
             $this->add_line_item_parameters($item, $i++);
         }
         // add order-level parameters
         $this->add_payment_parameters(array('AMT' => $order->get_total(), 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $order_subtotal - $total_discount, 'SHIPPINGAMT' => $order->get_total_shipping(), 'TAXAMT' => $order->get_total_tax(), 'INVNUM' => $order->paypal_express_invoice_prefix . SV_WC_Helper::str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number', WC_PayPal_Express::TEXT_DOMAIN))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id));
     }
 }
 /**
  * Get vendor commission per item for an order
  *
  * @param int $product_id
  * @param int $variation_id
  * @param array $item
  * @param int $order_id
  *
  * @return $commission_amount
  */
 public function get_item_commission($product_id, $variation_id, $item, $order_id, $item_id = '')
 {
     global $WCMp;
     $order = new WC_Order($order_id);
     $amount = 0;
     $commission = array();
     if (isset($WCMp->vendor_caps->payment_cap['commission_include_coupon'])) {
         $line_total = $order->get_item_total($item, false, false) * $item['qty'];
     } else {
         $line_total = $order->get_item_subtotal($item, false, false) * $item['qty'];
     }
     if ($product_id && $line_total) {
         $vendor_id = $order->get_item_meta($item_id, '_vendor_id', true);
         if ($vendor_id) {
             $vendor = get_wcmp_vendor($vendor_id);
         } else {
             $vendor = get_wcmp_product_vendors($product_id);
         }
         if ($vendor) {
             $commission = $this->get_commission_amount($product_id, $vendor->term_id, $variation_id, $item_id, $order);
             if (!empty($commission)) {
                 if ($WCMp->vendor_caps->payment_cap['commission_type'] == 'fixed_with_percentage') {
                     $amount = (double) $line_total * ((double) $commission['commission_val'] / 100) + (double) $commission['commission_fixed'];
                 } else {
                     if ($WCMp->vendor_caps->payment_cap['commission_type'] == 'fixed_with_percentage_qty') {
                         $amount = (double) $line_total * ((double) $commission['commission_val'] / 100) + (double) $commission['commission_fixed'] * $item['qty'];
                     } else {
                         if ($WCMp->vendor_caps->payment_cap['commission_type'] == 'percent') {
                             $amount = (double) $line_total * ((double) $commission['commission_val'] / 100);
                         } else {
                             if ($WCMp->vendor_caps->payment_cap['commission_type'] == 'fixed') {
                                 $amount = (double) $commission['commission_val'] * $item['qty'];
                             }
                         }
                     }
                 }
                 if (isset($WCMp->vendor_caps->payment_cap['revenue_sharing_mode'])) {
                     if ($WCMp->vendor_caps->payment_cap['revenue_sharing_mode'] == 'admin') {
                         $amount = (double) $line_total - (double) $amount;
                         if ($amount < 0) {
                             $amount = 0;
                         }
                     }
                 }
                 return apply_filters('vendor_commission_amount', $amount);
             }
         }
     }
     return apply_filters('vendor_commission_amount', $amount);
 }
 /**
  * ConfirmPayment
  *
  * Finalizes the checkout with PayPal's DoExpressCheckoutPayment API
  *
  * @FinalPaymentAmt (double) Final payment amount for the order.
  */
 function ConfirmPayment($FinalPaymentAmt)
 {
     /*
      * Display message to user if session has expired.
      */
     if (sizeof(WC()->cart->get_cart()) == 0) {
         wc_add_notice(sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage &rarr;</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'), "error");
     }
     /*
      * Check if the PayPal class has already been established.
      */
     if (!class_exists('Angelleye_PayPal')) {
         require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php';
     }
     /*
      * Create PayPal object.
      */
     $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? TRUE : FALSE, 'APIUsername' => $this->api_username, 'APIPassword' => $this->api_password, 'APISignature' => $this->api_signature);
     $PayPal = new Angelleye_PayPal($PayPalConfig);
     /*
      * Get data from WooCommerce object
      */
     if (!empty($this->confirm_order_id)) {
         $order = new WC_Order($this->confirm_order_id);
         $invoice_number = preg_replace("/[^0-9,.]/", "", $order->get_order_number());
         if ($order->customer_note) {
             $customer_notes = wptexturize($order->customer_note);
         }
         $shipping_first_name = $order->shipping_first_name;
         $shipping_last_name = $order->shipping_last_name;
         $shipping_address_1 = $order->shipping_address_1;
         $shipping_address_2 = $order->shipping_address_2;
         $shipping_city = $order->shipping_city;
         $shipping_state = $order->shipping_state;
         $shipping_postcode = $order->shipping_postcode;
         $shipping_country = $order->shipping_country;
     }
     // Prepare request arrays
     $DECPFields = array('token' => urlencode($this->get_session('TOKEN')), 'payerid' => urlencode($this->get_session('payer_id')), 'returnfmfdetails' => '', 'giftmessage' => $this->get_session('giftmessage'), 'giftreceiptenable' => $this->get_session('giftreceiptenable'), 'giftwrapname' => $this->get_session('giftwrapname'), 'giftwrapamount' => $this->get_session('giftwrapamount'), 'buyermarketingemail' => '', 'surveyquestion' => '', 'surveychoiceselected' => '', 'allowedpaymentmethod' => '');
     $Payments = array();
     $Payment = array('amt' => number_format($FinalPaymentAmt, 2, '.', ''), 'currencycode' => get_woocommerce_currency(), 'shippingdiscamt' => '', 'insuranceoptionoffered' => '', 'handlingamt' => '', 'desc' => '', 'custom' => '', 'invnum' => $this->invoice_id_prefix . $invoice_number, 'notifyurl' => '', 'shiptoname' => $shipping_first_name . ' ' . $shipping_last_name, 'shiptostreet' => $shipping_address_1, 'shiptostreet2' => $shipping_address_2, 'shiptocity' => $shipping_city, 'shiptostate' => $shipping_state, 'shiptozip' => $shipping_postcode, 'shiptocountrycode' => $shipping_country, 'shiptophonenum' => '', 'notetext' => $this->get_session('customer_notes'), 'allowedpaymentmethod' => '', 'paymentaction' => 'Sale', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '', 'sellerid' => '', 'sellerusername' => '', 'sellerregistrationdate' => '', 'softdescriptor' => '');
     $PaymentOrderItems = array();
     $ctr = 0;
     $ITEMAMT = 0;
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $values) {
             $_product = $order->get_product_from_item($values);
             $qty = absint($values['qty']);
             $sku = $_product->get_sku();
             $values['name'] = html_entity_decode($values['name'], ENT_NOQUOTES, 'UTF-8');
             if ($_product->product_type == 'variation') {
                 if (empty($sku)) {
                     $sku = $_product->parent->get_sku();
                 }
                 $item_meta = new WC_Order_Item_Meta($values['item_meta']);
                 $meta = $item_meta->display(true, true);
                 if (!empty($meta)) {
                     $values['name'] .= " - " . str_replace(", \n", " - ", $meta);
                 }
             }
             /*
              * Set price based on tax option.
              */
             if (get_option('woocommerce_prices_include_tax') == 'yes') {
                 $product_price = $order->get_item_subtotal($values, true, false);
             } else {
                 $product_price = $order->get_item_subtotal($values, false, true);
             }
             $Item = array('name' => $values['name'], 'desc' => '', 'amt' => $product_price, 'number' => $sku, 'qty' => $qty, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
             array_push($PaymentOrderItems, $Item);
             $ITEMAMT += $product_price * $values['qty'];
         }
         /**
          * Add custom Woo cart fees as line items
          */
         foreach (WC()->cart->get_fees() as $fee) {
             $Item = array('name' => $fee->name, 'desc' => '', 'amt' => number_format($fee->amount, 2, '.', ''), 'number' => $fee->id, 'qty' => 1, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => '');
             /**
              * The gift wrap amount actually has its own parameter in
              * DECP, so we don't want to include it as one of the line
              * items.
              */
             if ($Item['number'] != 'gift-wrap') {
                 array_push($PaymentOrderItems, $Item);
                 $ITEMAMT += $fee->amount * $Item['qty'];
             }
             $ctr++;
         }
         /*
          * Get discounts
          */
         if ($order->get_cart_discount() > 0) {
             foreach (WC()->cart->get_coupons('cart') as $code => $coupon) {
                 $Item = array('name' => 'Cart Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', ''));
                 array_push($PaymentOrderItems, $Item);
             }
             $ITEMAMT -= $order->get_cart_discount();
         }
         if ($order->get_order_discount() > 0) {
             foreach (WC()->cart->get_coupons('order') as $code => $coupon) {
                 $Item = array('name' => 'Order Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', ''));
                 array_push($PaymentOrderItems, $Item);
             }
             $ITEMAMT -= $order->get_order_discount();
         }
         /*
          * Set shipping and tax values.
          */
         if (get_option('woocommerce_prices_include_tax') == 'yes') {
             $shipping = $order->get_total_shipping() + $order->get_shipping_tax();
             $tax = 0;
         } else {
             $shipping = $order->get_total_shipping();
             $tax = $order->get_total_tax();
         }
         /*
          * Now that we have all items and subtotals
          * we can fill in necessary values.
          */
         $Payment['itemamt'] = number_format($ITEMAMT, 2, '.', '');
         // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order.
         /*
          * Set tax
          */
         if ($tax > 0) {
             $Payment['taxamt'] = number_format($tax, 2, '.', '');
             // Required if you specify itemized L_TAXAMT fields.  Sum of all tax items in this order.
         }
         /*
          * Set shipping
          */
         if ($shipping > 0) {
             $Payment['shippingamt'] = number_format($shipping, 2, '.', '');
             // Total shipping costs for this order.  If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT.
         }
     }
     $Payment['order_items'] = $PaymentOrderItems;
     array_push($Payments, $Payment);
     $UserSelectedOptions = array('shippingcalculationmode' => '', 'insuranceoptionselected' => '', 'shippingoptionisdefault' => '', 'shippingoptionamount' => '', 'shippingoptionname' => '');
     $PayPalRequestData = array('DECPFields' => $DECPFields, 'Payments' => $Payments);
     // Pass data into class for processing with PayPal and load the response array into $PayPalResult
     $PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData);
     /*
      * Log API result
      */
     $this->add_log('Test Mode: ' . $this->testmode);
     $this->add_log('Endpoint: ' . $this->API_Endpoint);
     $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : '';
     $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : '';
     $this->add_log('Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true));
     $this->add_log('Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true));
     /*
      * Error handling
      */
     if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) {
         $this->remove_session('TOKEN');
     }
     /*
      * Return the class library result array.
      */
     return $PayPalResult;
 }
 /**
  * Process the payment and return the result
  *
  * @access public
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $this->init_mijireh();
     $mj_order = new Mijireh_Order();
     $wc_order = new WC_Order($order_id);
     // add items to order
     $items = $wc_order->get_items();
     foreach ($items as $item) {
         $product = $wc_order->get_product_from_item($item);
         if (get_option('woocommerce_prices_include_tax') == 'yes') {
             $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, true, false), $item['qty'], $product->get_sku());
         } else {
             $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, false, true), $item['qty'], $product->get_sku());
         }
     }
     // Handle fees
     $items = $wc_order->get_fees();
     foreach ($items as $item) {
         $mj_order->add_item($item['name'], number_format($item['line_total'], 2, '.', ','), 1, '');
     }
     // add billing address to order
     $billing = new Mijireh_Address();
     $billing->first_name = $wc_order->billing_first_name;
     $billing->last_name = $wc_order->billing_last_name;
     $billing->street = $wc_order->billing_address_1;
     $billing->apt_suite = $wc_order->billing_address_2;
     $billing->city = $wc_order->billing_city;
     $billing->state_province = $wc_order->billing_state;
     $billing->zip_code = $wc_order->billing_postcode;
     $billing->country = $wc_order->billing_country;
     $billing->company = $wc_order->billing_company;
     $billing->phone = $wc_order->billing_phone;
     if ($billing->validate()) {
         $mj_order->set_billing_address($billing);
     }
     // add shipping address to order
     $shipping = new Mijireh_Address();
     $shipping->first_name = $wc_order->shipping_first_name;
     $shipping->last_name = $wc_order->shipping_last_name;
     $shipping->street = $wc_order->shipping_address_1;
     $shipping->apt_suite = $wc_order->shipping_address_2;
     $shipping->city = $wc_order->shipping_city;
     $shipping->state_province = $wc_order->shipping_state;
     $shipping->zip_code = $wc_order->shipping_postcode;
     $shipping->country = $wc_order->shipping_country;
     $shipping->company = $wc_order->shipping_company;
     if ($shipping->validate()) {
         $mj_order->set_shipping_address($shipping);
     }
     // set order name
     $mj_order->first_name = $wc_order->billing_first_name;
     $mj_order->last_name = $wc_order->billing_last_name;
     $mj_order->email = $wc_order->billing_email;
     // set order totals
     $mj_order->total = $wc_order->get_total();
     $mj_order->discount = $wc_order->get_total_discount();
     if (get_option('woocommerce_prices_include_tax') == 'yes') {
         $mj_order->shipping = round($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2);
         $mj_order->show_tax = false;
     } else {
         $mj_order->shipping = round($wc_order->get_total_shipping(), 2);
         $mj_order->tax = $wc_order->get_total_tax();
     }
     // add meta data to identify woocommerce order
     $mj_order->add_meta_data('wc_order_id', $order_id);
     // Set URL for mijireh payment notificatoin - use WC API
     $mj_order->return_url = str_replace('https:', 'http:', add_query_arg('wc-api', 'WC_Gateway_Mijireh', home_url('/')));
     // Identify woocommerce
     $mj_order->partner_id = 'woo';
     try {
         $mj_order->create();
         $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url);
         return $result;
     } catch (Mijireh_Exception $e) {
         wc_add_notice(__('Mijireh error:', 'woocommerce') . $e->getMessage(), 'error');
     }
 }
 function order_data($post_id)
 {
     global $wpdb;
     $WooCommerceNFe_Format = new WooCommerceNFe_Format();
     $order = new WC_Order($post_id);
     $coupons = $order->get_used_coupons();
     $coupons_percentage = array();
     $total_discount = 0;
     $data = array();
     if ($coupons) {
         foreach ($coupons as $coupon_code) {
             $coupon_obj = new WC_Coupon($coupon_code);
             if ($coupon_obj->discount_type == 'percent') {
                 $coupons_percentage[] = $coupon_obj->coupon_amount;
             }
         }
     }
     if ($order->get_fees()) {
         foreach ($order->get_fees() as $key => $item) {
             if ($item['line_total'] < 0) {
                 $discount = $item['line_total'] * -1;
                 $total_discount = $discount + $total_discount;
             } else {
                 $codigo_ean = get_option('wc_settings_woocommercenfe_ean');
                 $codigo_ncm = get_option('wc_settings_woocommercenfe_ncm');
                 $codigo_cest = get_option('wc_settings_woocommercenfe_cest');
                 $origem = get_option('wc_settings_woocommercenfe_origem');
                 $imposto = get_option('wc_settings_woocommercenfe_imposto');
                 $data['produtos'][] = array('nome' => $item['name'], 'sku' => $product->get_sku(), 'ean' => $codigo_ean, 'ncm' => $codigo_ncm, 'cest' => $codigo_cest, 'quantidade' => 1, 'unidade' => 'UN', 'peso' => '0.100', 'origem' => (int) $origem, 'subtotal' => number_format($item['line_subtotal'], 2), 'total' => number_format($item['line_total'], 2), 'classe_imposto' => $imposto);
             }
         }
     }
     $total_discount = $order->get_total_discount() + $total_discount;
     // Order
     $data = array('ID' => $post_id, 'operacao' => 1, 'natureza_operacao' => get_option('wc_settings_woocommercenfe_natureza_operacao'), 'modelo' => 1, 'emissao' => 1, 'finalidade' => 1, 'ambiente' => (int) get_option('wc_settings_woocommercenfe_ambiente'));
     $data['pedido'] = array('pagamento' => 0, 'presenca' => 2, 'modalidade_frete' => 0, 'frete' => get_post_meta($order->id, '_order_shipping', true), 'desconto' => $total_discount, 'total' => $order->order_total);
     //Informações COmplementares ao Fisco
     $fiscoinf = get_option('wc_settings_woocommercenfe_fisco_inf');
     if (!empty($fiscoinf) && strlen($fiscoinf) <= 2000) {
         $data['pedido']['informacoes_fisco'] = $fiscoinf;
     }
     //Informações Complementares ao Consumidor
     $consumidorinf = get_option('wc_settings_woocommercenfe_cons_inf');
     if (!empty($consumidorinf) && strlen($consumidorinf) <= 2000) {
         $data['pedido']['informacoes_complementares'] = $consumidorinf;
     }
     // Customer
     $tipo_pessoa = get_post_meta($post_id, '_billing_persontype', true);
     if (!$tipo_pessoa) {
         $tipo_pessoa = 1;
     }
     if ($tipo_pessoa == 1) {
         $data['cliente'] = array('cpf' => $WooCommerceNFe_Format->cpf(get_post_meta($post_id, '_billing_cpf', true)), 'nome_completo' => get_post_meta($post_id, '_billing_first_name', true) . ' ' . get_post_meta($post_id, '_billing_last_name', true), 'endereco' => get_post_meta($post_id, '_shipping_address_1', true), 'complemento' => get_post_meta($post_id, '_shipping_address_2', true), 'numero' => get_post_meta($post_id, '_shipping_number', true), 'bairro' => get_post_meta($post_id, '_shipping_neighborhood', true), 'cidade' => get_post_meta($post_id, '_shipping_city', true), 'uf' => get_post_meta($post_id, '_shipping_state', true), 'cep' => $WooCommerceNFe_Format->cep(get_post_meta($post_id, '_shipping_postcode', true)), 'telefone' => get_user_meta($post_id, 'billing_phone', true), 'email' => get_post_meta($post_id, '_billing_email', true));
     }
     if ($tipo_pessoa == 2) {
         $data['cliente'] = array('cnpj' => $WooCommerceNFe_Format->cnpj(get_post_meta($post_id, '_billing_cnpj', true)), 'razao_social' => get_post_meta($post_id, '_billing_company', true), 'ie' => get_post_meta($post_id, '_billing_ie', true), 'endereco' => get_post_meta($post_id, '_shipping_address_1', true), 'complemento' => get_post_meta($post_id, '_shipping_address_2', true), 'numero' => get_post_meta($post_id, '_shipping_number', true), 'bairro' => get_post_meta($post_id, '_shipping_neighborhood', true), 'cidade' => get_post_meta($post_id, '_shipping_city', true), 'uf' => get_post_meta($post_id, '_shipping_state', true), 'cep' => $WooCommerceNFe_Format->cep(get_post_meta($post_id, '_shipping_postcode', true)), 'telefone' => get_user_meta($post_id, 'billing_phone', true), 'email' => get_post_meta($post_id, '_billing_email', true));
     }
     // Products
     foreach ($order->get_items() as $key => $item) {
         $product_id = $item['product_id'];
         $variation_id = $item['variation_id'];
         $ignorar_nfe = get_post_meta($product_id, '_nfe_ignorar_nfe', true);
         if ($ignorar_nfe == 1 || $order->get_item_subtotal($item, false, false) == 0) {
             $data['pedido']['total'] -= $item['line_subtotal'];
             if ($coupons_percentage) {
                 foreach ($coupons_percentage as $percentage) {
                     $data['pedido']['total'] += $percentage / 100 * $item['line_subtotal'];
                     $data['pedido']['desconto'] -= $percentage / 100 * $item['line_subtotal'];
                 }
             }
             $data['pedido']['total'] = number_format($data['pedido']['total'], 2);
             $data['pedido']['desconto'] = number_format($data['pedido']['desconto'], 2);
             continue;
         }
         $emitir = apply_filters('emitir_nfe_produto', true, $product_id);
         if ($variation_id) {
             $emitir = apply_filters('emitir_nfe_produto', true, $variation_id);
         }
         if ($emitir) {
             $product = $order->get_product_from_item($item);
             // Vars
             $codigo_ean = get_post_meta($product_id, '_nfe_codigo_ean', true);
             $codigo_ncm = get_post_meta($product_id, '_nfe_codigo_ncm', true);
             $codigo_cest = get_post_meta($product_id, '_nfe_codigo_cest', true);
             $origem = get_post_meta($product_id, '_nfe_origem', true);
             $imposto = get_post_meta($product_id, '_nfe_classe_imposto', true);
             $peso = $product->get_weight();
             if (!$peso) {
                 $peso = '0.100';
             }
             if (!$codigo_ean) {
                 $codigo_ean = get_option('wc_settings_woocommercenfe_ean');
             }
             if (!$codigo_ncm) {
                 $codigo_ncm = get_option('wc_settings_woocommercenfe_ncm');
             }
             if (!$codigo_cest) {
                 $codigo_cest = get_option('wc_settings_woocommercenfe_cest');
             }
             if (!is_numeric($origem)) {
                 $origem = get_option('wc_settings_woocommercenfe_origem');
             }
             if (!$imposto) {
                 $imposto = get_option('wc_settings_woocommercenfe_imposto');
             }
             // Attributes
             $variacoes = '';
             foreach (array_keys($item['item_meta']) as $meta) {
                 if (strpos($meta, 'pa_') !== false) {
                     $atributo = $item[$meta];
                     $nome_atributo = str_replace('pa_', '', $meta);
                     $nome_atributo = $wpdb->get_var("SELECT attribute_label FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name = '{$nome_atributo}'");
                     $valor = strtoupper($item[$meta]);
                     $variacoes .= ' - ' . strtoupper($nome_atributo) . ': ' . $valor;
                 }
             }
             $data['produtos'][] = array('nome' => $item['name'] . $variacoes, 'sku' => $product->get_sku(), 'ean' => $codigo_ean, 'ncm' => $codigo_ncm, 'cest' => $codigo_cest, 'quantidade' => $item['qty'], 'unidade' => 'UN', 'peso' => $peso, 'origem' => (int) $origem, 'subtotal' => number_format($order->get_item_subtotal($item, false, false), 2), 'total' => number_format($order->get_line_total($item, false, false), 2), 'classe_imposto' => $imposto);
         }
     }
     return $data;
 }
Esempio n. 11
0
function ceske_sluzby_srovname_mereni_konverzi($order_id)
{
    $klic = get_option('wc_ceske_sluzby_srovname_konverze-objednavky');
    if (!empty($klic)) {
        $order = new WC_Order($order_id);
        $products = $order->get_items();
        ?>

<script type="text/javascript">
var _srt = _srt || [];
    _srt.push(['_setShop', '<?php 
        echo $klic;
        ?>
']);
    _srt.push(['_setTransId', '<?php 
        echo $order_id;
        ?>
']);
    <?php 
        foreach ($products as $product) {
            $cena = wc_format_decimal($order->get_item_subtotal($product));
            echo "_srt.push(['_addProduct', '" . $product['name'] . "', '" . $cena . "', '" . $product['qty'] . "']);";
        }
        ?>
    _srt.push(['_trackTrans']);

(function() {
    var s = document.createElement("script");
    s.type = "text/javascript";
    s.async = true;
    s.src = ("https:" == document.location.protocol ? "https" : "http") + "://www.srovname.cz/js/track-trans.js";
    var x = document.getElementsByTagName("script")[0];
    x.parentNode.insertBefore(s, x);
})();
</script>

<?php 
    }
}
        /**
         * Generate form
         *
         * @param mixed $order_id
         * @return string
         */
        public function generate_dokuonecheckout_form($order_id)
        {
            global $woocommerce;
            global $wpdb;
            static $basket;
            $order = new WC_Order($order_id);
            $counter = 0;
            foreach ($order->get_items() as $item) {
                $BASKET = $basket . $item['name'] . ',' . $order->get_item_subtotal($item) . ',' . $item['qty'] . ',' . $order->get_line_subtotal($item) . ';';
            }
            $BASKET = "";
            // Order Items
            if (sizeof($order->get_items()) > 0) {
                foreach ($order->get_items() as $item) {
                    $BASKET .= str_replace(",", "", $item['name']) . "," . number_format($order->get_item_subtotal($item), 2, '.', '') . "," . $item['qty'] . "," . number_format($order->get_item_subtotal($item) * $item['qty'], 2, '.', '') . ";";
                }
            }
            // Shipping Fee
            if ($order->order_shipping > 0) {
                $BASKET .= "Shipping Fee," . number_format($order->order_shipping, 2, '.', '') . ",1," . number_format($order->order_shipping, 2, '.', '') . ";";
            }
            // Tax
            if ($order->get_total_tax() > 0) {
                $BASKET .= "Tax," . $order->get_total_tax() . ",1," . $order->get_total_tax() . ";";
            }
            // Fees
            if (sizeof($order->get_fees()) > 0) {
                $fee_counter = 0;
                foreach ($order->get_fees() as $item) {
                    $fee_counter++;
                    $BASKET .= "Fee Item," . $item['line_total'] . ",1," . $item['line_total'] . ";";
                }
            }
            $BASKET = preg_replace("/([^a-zA-Z0-9.\\-,=:;&% ]+)/", " ", $BASKET);
            $MALL_ID = trim($this->mall_id);
            $SHARED_KEY = trim($this->shared_key);
            $CHAIN = trim($this->chain);
            $URL = $this->url;
            $CURRENCY = 360;
            $TRANSIDMERCHANT = $order_id;
            $NAME = trim($order->billing_first_name . " " . $order->billing_last_name);
            $EMAIL = trim($order->billing_email);
            $ADDRESS = trim($order->billing_address_1 . " " . $order->billing_address_2);
            $CITY = trim($order->billing_city);
            $ZIPCODE = trim($order->billing_postcode);
            $STATE = trim($order->billing_city);
            $REQUEST_DATETIME = date("YmdHis");
            $IP_ADDRESS = $this->getipaddress();
            $PROCESS_DATETIME = date("Y-m-d H:i:s");
            $PROCESS_TYPE = "REQUEST";
            $AMOUNT = number_format($order->order_total, 2, '.', '');
            $PHONE = trim($order->billing_phone);
            $PAYMENT_CHANNEL = "";
            $SESSION_ID = COOKIEHASH;
            $WORDS = sha1(trim($AMOUNT) . trim($MALL_ID) . trim($SHARED_KEY) . trim($TRANSIDMERCHANT));
            $dokuonecheckout_args = array('MALLID' => $MALL_ID, 'CHAINMERCHANT' => $CHAIN, 'AMOUNT' => $AMOUNT, 'PURCHASEAMOUNT' => $AMOUNT, 'TRANSIDMERCHANT' => $TRANSIDMERCHANT, 'WORDS' => $WORDS, 'REQUESTDATETIME' => $REQUEST_DATETIME, 'CURRENCY' => $CURRENCY, 'PURCHASECURRENCY' => $CURRENCY, 'SESSIONID' => $SESSION_ID, 'PAYMENTCHANNEL' => $PAYMENT_CHANNEL, 'NAME' => $NAME, 'EMAIL' => $EMAIL, 'HOMEPHONE' => $PHONE, 'MOBILEPHONE' => $PHONE, 'BASKET' => $BASKET, 'ADDRESS' => $ADDRESS, 'CITY' => $CITY, 'STATE' => $STATE, 'ZIPCODE' => $ZIPCODE);
            $trx['ip_address'] = $IP_ADDRESS;
            $trx['process_type'] = $PROCESS_TYPE;
            $trx['process_datetime'] = $PROCESS_DATETIME;
            $trx['transidmerchant'] = $TRANSIDMERCHANT;
            $trx['amount'] = $AMOUNT;
            $trx['session_id'] = $SESSION_ID;
            $trx['words'] = $WORDS;
            $trx['message'] = "Transaction request start";
            # Insert transaction request to table dokuonecheckout
            $this->add_dokuonecheckout($trx);
            // Form
            $dokuonecheckout_args_array = array();
            foreach ($dokuonecheckout_args as $key => $value) {
                $dokuonecheckout_args_array[] = "<input type='hidden' name='{$key}' value='{$value}' />";
            }
            return '<form action="' . $URL . '" method="post" id="dokuonecheckout_payment_form">' . implode(" \r\n", $dokuonecheckout_args_array) . '<input type="submit" class="button-alt" id="submit_dokuonecheckout_payment_form" value="' . __('Pay via DOKU', 'woocommerce') . '" />
										<!--
										<a class="button cancel" href="' . $order->get_cancel_order_url() . '">' . __('Cancel order &amp; restore cart', 'woocommerce') . '</a>
										-->

										<script type="text/javascript">
										jQuery(function(){
										jQuery("body").block(
										{
												message: "<img src=\\"' . $woocommerce->plugin_url() . '/assets/images/ajax-loader.gif\\" alt=\\"Redirecting...\\" style=\\"float:left; margin-right: 10px;\\" />' . __('Thank you for your order. We are now redirecting you to dokuonecheckout to make payment.', 'woocommerce') . '",
												overlayCSS:
										{
										background: "#fff",
										opacity: 0.6
										},
										css: {
													padding:        20,
													textAlign:      "center",
													color:          "#555",
													border:         "3px solid #aaa",
													backgroundColor:"#fff",
													cursor:         "wait",
													lineHeight:     "32px"
												}
										});
										jQuery("#submit_dokuonecheckout_payment_form").click();});
										</script>
										</form>';
        }
 /**
  * Set up the payment details for a DoExpressCheckoutPayment or DoReferenceTransaction request
  *
  * @since 2.0.9
  * @param WC_Order $order order object
  * @param string $type the type of transaction for the payment
  * @param bool $use_deprecated_params whether to use deprecated PayPal NVP parameters (required for DoReferenceTransaction API calls)
  */
 protected function add_payment_details_parameters(WC_Order $order, $type, $use_deprecated_params = false)
 {
     $calculated_total = 0;
     $order_subtotal = 0;
     $item_count = 0;
     $order_items = array();
     // add line items
     foreach ($order->get_items() as $item) {
         $product = new WC_Product($item['product_id']);
         $order_items[] = array('NAME' => wcs_get_paypal_item_name($product->get_title()), 'DESC' => $this->get_item_description($item, $product), 'AMT' => $this->round($order->get_item_subtotal($item)), 'QTY' => !empty($item['qty']) ? absint($item['qty']) : 1, 'ITEMURL' => $product->get_permalink());
         $order_subtotal += $item['line_total'];
     }
     // add fees
     foreach ($order->get_fees() as $fee) {
         $order_items[] = array('NAME' => wcs_get_paypal_item_name($fee['name']), 'AMT' => $this->round($fee['line_total']), 'QTY' => 1);
         $order_subtotal += $fee['line_total'];
     }
     // add discounts
     if ($order->get_total_discount() > 0) {
         $order_items[] = array('NAME' => __('Total Discount', 'woocommerce-subscriptions'), 'QTY' => 1, 'AMT' => -$this->round($order->get_total_discount()));
     }
     if ($this->skip_line_items($order)) {
         $total_amount = $this->round($order->get_total());
         // calculate the total as PayPal would
         $calculated_total += $this->round($order_subtotal + $order->get_cart_tax()) + $this->round($order->get_total_shipping() + $order->get_shipping_tax());
         // offset the discrepency between the WooCommerce cart total and PayPal's calculated total by adjusting the order subtotal
         if ($total_amount !== $calculated_total) {
             $order_subtotal = $order_subtotal - ($calculated_total - $total_amount);
         }
         $item_names = array();
         foreach ($order_items as $item) {
             $item_names[] = sprintf('%1$s x %2$s', $item['NAME'], $item['QTY']);
         }
         // add a single item for the entire order
         $this->add_line_item_parameters(array('NAME' => sprintf(__('%s - Order', 'woocommerce-subscriptions'), get_option('blogname')), 'DESC' => wcs_get_paypal_item_name(implode(', ', $item_names)), 'AMT' => $this->round($order_subtotal + $order->get_cart_tax()), 'QTY' => 1), 0, $use_deprecated_params);
         // add order-level parameters
         //  - Do not sent the TAXAMT due to rounding errors
         if ($use_deprecated_params) {
             $this->add_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal + $order->get_cart_tax()), 'SHIPPINGAMT' => $this->round($order->get_total_shipping() + $order->get_shipping_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key))));
         } else {
             $this->add_payment_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal + $order->get_cart_tax()), 'SHIPPINGAMT' => $this->round($order->get_total_shipping() + $order->get_shipping_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key))));
         }
     } else {
         // add individual order items
         foreach ($order_items as $item) {
             $this->add_line_item_parameters($item, $item_count++, $use_deprecated_params);
             $calculated_total += $this->round($item['AMT'] * $item['QTY']);
         }
         // add shipping and tax to calculated total
         $calculated_total += $this->round($order->get_total_shipping()) + $this->round($order->get_total_tax());
         $total_amount = $this->round($order->get_total());
         // add order-level parameters
         if ($use_deprecated_params) {
             $this->add_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal), 'SHIPPINGAMT' => $this->round($order->get_total_shipping()), 'TAXAMT' => $this->round($order->get_total_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key))));
         } else {
             $this->add_payment_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal), 'SHIPPINGAMT' => $this->round($order->get_total_shipping()), 'TAXAMT' => $this->round($order->get_total_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key))));
         }
         // offset the discrepency between the WooCommerce cart total and PayPal's calculated total by adjusting the cost of the first item
         if ($total_amount !== $calculated_total) {
             $this->parameters['L_PAYMENTREQUEST_0_AMT0'] = $this->parameters['L_PAYMENTREQUEST_0_AMT0'] - ($calculated_total - $total_amount);
         }
     }
 }
 /**
  * Charge a payment against a reference token
  *
  * @link https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECReferenceTxns/#id094UM0DA0HS
  * @link https://developer.paypal.com/docs/classic/api/merchant/DoReferenceTransaction_API_Operation_NVP/
  *
  * @param string $reference_id the ID of a refrence object, e.g. billing agreement ID.
  * @param WC_Order $order order object
  * @param array $args {
  *     @type string 'payment_type'         (Optional) Specifies type of PayPal payment you require for the billing agreement. It is one of the following values. 'Any' or 'InstantOnly'. Echeck is not supported for DoReferenceTransaction requests.
  *     @type string 'payment_action'       How you want to obtain payment. It is one of the following values: 'Authorization' - this payment is a basic authorization subject to settlement with PayPal Authorization and Capture; or 'Sale' - This is a final sale for which you are requesting payment.
  *     @type string 'return_fraud_filters' (Optional) Flag to indicate whether you want the results returned by Fraud Management Filters. By default, you do not receive this information.
  * }
  * @since 2.0
  */
 public function do_reference_transaction($reference_id, $order, $args = array())
 {
     $defaults = array('amount' => $order->get_total(), 'payment_type' => 'Any', 'payment_action' => 'Sale', 'return_fraud_filters' => 1, 'notify_url' => WC()->api_request_url('WC_Gateway_Paypal'), 'invoice_number' => wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number', 'woocommerce-subscriptions'))), 'custom' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key)));
     $args = wp_parse_args($args, $defaults);
     $this->set_method('DoReferenceTransaction');
     // set base params
     $this->add_parameters(array('REFERENCEID' => $reference_id, 'BUTTONSOURCE' => 'WooThemes_Cart', 'RETURNFMFDETAILS' => $args['return_fraud_filters'], 'AMT' => $order->get_total(), 'CURRENCYCODE' => $order->get_order_currency(), 'INVNUM' => $args['invoice_number'], 'PAYMENTACTION' => $args['payment_action'], 'NOTIFYURL' => $args['notify_url'], 'CUSTOM' => $args['custom']));
     $order_subtotal = $i = 0;
     $order_items = array();
     // add line items
     foreach ($order->get_items() as $item) {
         $order_items[] = array('NAME' => wcs_get_paypal_item_name($item['name']), 'AMT' => $order->get_item_subtotal($item), 'QTY' => !empty($item['qty']) ? absint($item['qty']) : 1);
         $order_subtotal += $item['line_total'];
     }
     // add fees
     foreach ($order->get_fees() as $fee) {
         $order_items[] = array('NAME' => wcs_get_paypal_item_name($fee['name']), 'AMT' => $fee['line_total'], 'QTY' => 1);
         $order_subtotal += $fee['line_total'];
     }
     // WC 2.3+, no after-tax discounts
     if ($order->get_total_discount() > 0) {
         $order_items[] = array('NAME' => __('Total Discount', 'woocommerce-subscriptions'), 'QTY' => 1, 'AMT' => -$order->get_total_discount());
     }
     if ($order->prices_include_tax) {
         $item_names = array();
         foreach ($order_items as $item) {
             $item_names[] = sprintf('%s x %s', $item['NAME'], $item['QTY']);
         }
         // add a single item for the entire order
         $this->add_line_item_parameters(array('NAME' => sprintf(__('%s - Order', 'woocommerce-subscriptions'), get_option('blogname')), 'DESC' => wcs_get_paypal_item_name(implode(', ', $item_names)), 'AMT' => $order_subtotal + $order->get_cart_tax(), 'QTY' => 1), 0);
         // add order-level parameters - do not send the TAXAMT due to rounding errors
         $this->add_payment_parameters(array('ITEMAMT' => $order_subtotal + $order->get_cart_tax(), 'SHIPPINGAMT' => $order->get_total_shipping() + $order->get_shipping_tax()));
     } else {
         // add individual order items
         foreach ($order_items as $item) {
             $this->add_line_item_parameters($item, $i++);
         }
         // add order-level parameters
         $this->add_payment_parameters(array('ITEMAMT' => $order_subtotal, 'SHIPPINGAMT' => $order->get_total_shipping(), 'TAXAMT' => $order->get_total_tax()));
     }
 }