function rpgc_add_giftcard_to_paypal($paypal_args)
{
    global $woocommerce;
    $giftCardPayment = WC()->session->giftcard_payment;
    $custom = unserialize($paypal_args["custom"]);
    $order = new WC_Order($custom[0]);
    if ($giftCardPayment != NULL) {
        if (!(get_option('woocommerce_prices_include_tax') == 'yes' || $order->get_order_discount() > 0 || sizeof($order->get_items()) + sizeof($order->get_fees()) >= 9)) {
            //$paypal_args['discount_amount_cart'] = 0;
            //} else {
            if (isset($paypal_args['discount_amount_cart'])) {
                $paypal_args['discount_amount_cart'] = $paypal_args['discount_amount_cart'] + $giftCardPayment;
            } else {
                $paypal_args['discount_amount_cart'] = $giftCardPayment;
            }
        }
    }
    return apply_filters('rpgc_send_giftcard_to_paypal', $paypal_args);
}
 /**
  * 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);
         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, false), $item['qty'], $product->get_sku());
         }
     }
     // Handle fees
     $items = $wc_order->get_fees();
     foreach ($items as $item) {
         $mj_order->add_item($item['name'], $item['line_total'], 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_order_total();
     $mj_order->discount = $wc_order->get_total_discount();
     if (get_option('woocommerce_prices_include_tax') == 'yes') {
         $mj_order->shipping = $wc_order->get_shipping() + $wc_order->get_shipping_tax();
         $mj_order->show_tax = false;
     } else {
         $mj_order->shipping = $wc_order->get_shipping();
         $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) {
         $woocommerce->add_error(__('Mijireh error:', 'woocommerce') . $e->getMessage());
     }
 }
Exemple #3
0
 /**
  * Test: get_fees
  */
 function test_get_fees()
 {
     $object = new WC_Order();
     $item = new WC_Order_Item_Fee();
     $item->set_props(array('name' => 'Some Fee', 'tax_status' => 'taxable', 'total' => '100', 'tax_class' => ''));
     $object->add_item($item);
     $this->assertCount(1, $object->get_fees());
 }
 /**
  * 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);
 }
 /**
  * When a new order is inserted, add subscriptions related order meta.
  *
  * @since 1.0
  */
 public static function add_order_meta($order_id, $posted)
 {
     global $woocommerce;
     if (!WC_Subscriptions_Cart::cart_contains_subscription_renewal('child') && WC_Subscriptions_Order::order_contains_subscription($order_id)) {
         // This works because the 'woocommerce_add_order_item_meta' runs before the 'woocommerce_checkout_update_order_meta' hook
         // Set the recurring totals so totals display correctly on order page
         update_post_meta($order_id, '_order_recurring_discount_cart', WC_Subscriptions_Cart::get_recurring_discount_cart());
         update_post_meta($order_id, '_order_recurring_discount_cart_tax', WC_Subscriptions_Cart::get_recurring_discount_cart_tax());
         update_post_meta($order_id, '_order_recurring_discount_total', WC_Subscriptions_Cart::get_recurring_discount_total());
         update_post_meta($order_id, '_order_recurring_shipping_tax_total', WC_Subscriptions_Cart::get_recurring_shipping_tax_total());
         update_post_meta($order_id, '_order_recurring_shipping_total', WC_Subscriptions_Cart::get_recurring_shipping_total());
         update_post_meta($order_id, '_order_recurring_tax_total', WC_Subscriptions_Cart::get_recurring_total_tax());
         update_post_meta($order_id, '_order_recurring_total', WC_Subscriptions_Cart::get_recurring_total());
         // Set the recurring payment method - it starts out the same as the original by may change later
         update_post_meta($order_id, '_recurring_payment_method', get_post_meta($order_id, '_payment_method', true));
         update_post_meta($order_id, '_recurring_payment_method_title', get_post_meta($order_id, '_payment_method_title', true));
         $order = new WC_Order($order_id);
         $order_fees = $order->get_fees();
         // the fee order items have already been set, we just need to to add the recurring total meta
         $cart_fees = $woocommerce->cart->get_fees();
         foreach ($order->get_fees() as $item_id => $order_fee) {
             // Find the matching fee in the cart
             foreach ($cart_fees as $fee_index => $cart_fee) {
                 if (sanitize_title($order_fee['name']) == $cart_fee->id) {
                     woocommerce_add_order_item_meta($item_id, '_recurring_line_total', wc_format_decimal($cart_fee->recurring_amount));
                     woocommerce_add_order_item_meta($item_id, '_recurring_line_tax', wc_format_decimal($cart_fee->recurring_tax));
                     unset($cart_fees[$fee_index]);
                     break;
                 }
             }
         }
         // Get recurring taxes into same format as _order_taxes
         $order_recurring_taxes = array();
         foreach (WC_Subscriptions_Cart::get_recurring_taxes() as $tax_key => $tax_amount) {
             $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => WC_Tax::get_rate_code($tax_key), 'order_item_type' => 'recurring_tax'));
             if ($item_id) {
                 wc_add_order_item_meta($item_id, 'rate_id', $tax_key);
                 wc_add_order_item_meta($item_id, 'label', WC_Tax::get_rate_label($tax_key));
                 wc_add_order_item_meta($item_id, 'compound', absint(WC_Tax::is_compound($tax_key) ? 1 : 0));
                 wc_add_order_item_meta($item_id, 'tax_amount', wc_format_decimal(isset(WC()->cart->recurring_taxes[$tax_key]) ? WC()->cart->recurring_taxes[$tax_key] : 0));
                 wc_add_order_item_meta($item_id, 'shipping_tax_amount', wc_format_decimal(isset(WC()->cart->recurring_shipping_taxes[$tax_key]) ? WC()->cart->recurring_shipping_taxes[$tax_key] : 0));
             }
         }
         $payment_gateways = $woocommerce->payment_gateways->payment_gateways();
         if ('yes' == get_option(WC_Subscriptions_Admin::$option_prefix . '_turn_off_automatic_payments', 'no')) {
             update_post_meta($order_id, '_wcs_requires_manual_renewal', 'true');
         } elseif (isset($payment_gateways[$posted['payment_method']]) && !$payment_gateways[$posted['payment_method']]->supports('subscriptions')) {
             update_post_meta($order_id, '_wcs_requires_manual_renewal', 'true');
         }
         $cart_item = WC_Subscriptions_Cart::cart_contains_subscription_renewal();
         if (isset($cart_item['subscription_renewal']) && 'parent' == $cart_item['subscription_renewal']['role']) {
             update_post_meta($order_id, '_original_order', $cart_item['subscription_renewal']['original_order']);
         }
         // WC 2.1+
         if (!WC_Subscriptions::is_woocommerce_pre('2.1')) {
             // Recurring coupons
             if ($applied_coupons = $woocommerce->cart->get_coupons()) {
                 foreach ($applied_coupons as $code => $coupon) {
                     if (!isset($woocommerce->cart->recurring_coupon_discount_amounts[$code])) {
                         continue;
                     }
                     $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $code, 'order_item_type' => 'recurring_coupon'));
                     // Add line item meta
                     if ($item_id) {
                         woocommerce_add_order_item_meta($item_id, 'discount_amount', isset($woocommerce->cart->recurring_coupon_discount_amounts[$code]) ? $woocommerce->cart->recurring_coupon_discount_amounts[$code] : 0);
                     }
                 }
             }
             // Add recurring shipping order items
             if (WC_Subscriptions_Cart::cart_contains_subscriptions_needing_shipping()) {
                 $packages = $woocommerce->shipping->get_packages();
                 $checkout = $woocommerce->checkout();
                 foreach ($packages as $i => $package) {
                     if (isset($package['rates'][$checkout->shipping_methods[$i]])) {
                         $method = $package['rates'][$checkout->shipping_methods[$i]];
                         $item_id = woocommerce_add_order_item($order_id, array('order_item_name' => $method->label, 'order_item_type' => 'recurring_shipping'));
                         if ($item_id) {
                             woocommerce_add_order_item_meta($item_id, 'method_id', $method->id);
                             woocommerce_add_order_item_meta($item_id, 'cost', WC_Subscriptions::format_total($method->cost));
                             woocommerce_add_order_item_meta($item_id, 'taxes', array_map('wc_format_decimal', $method->taxes));
                             do_action('woocommerce_subscriptions_add_recurring_shipping_order_item', $order_id, $item_id, $i);
                         }
                     }
                 }
             }
             // Remove shipping on original order if it was added but is not required
             if (!WC_Subscriptions_Cart::charge_shipping_up_front()) {
                 foreach ($order->get_shipping_methods() as $order_item_id => $shipping_method) {
                     woocommerce_update_order_item_meta($order_item_id, 'cost', WC_Subscriptions::format_total(0));
                 }
             }
         } else {
             update_post_meta($order_id, '_recurring_shipping_method', get_post_meta($order_id, '_shipping_method', true), true);
             update_post_meta($order_id, '_recurring_shipping_method_title', get_post_meta($order_id, '_shipping_method_title', true), true);
         }
     }
 }
 /**
  * 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;
 }
 /**
  * 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);
         }
     }
 }
 /**
  * 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');
     }
 }
 /**
  * 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));
     }
 }
Exemple #10
0
 public function generate_invoice($orderId)
 {
     global $wpdb, $woocommerce;
     $order = new WC_Order($orderId);
     $order_items = $order->get_items();
     //Build Xml
     $szamla = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><xmlszamla xmlns="http://www.szamlazz.hu/xmlszamla" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.szamlazz.hu/xmlszamla xmlszamla.xsd"></xmlszamla>');
     //If custom details
     if (isset($_POST['note']) && isset($_POST['deadline']) && isset($_POST['completed'])) {
         $note = $_POST['note'];
         $deadline = $_POST['deadline'];
         $complated_date = $_POST['completed'];
     } else {
         $note = get_option('wc_szamlazz_note');
         $deadline = get_option('wc_szamlazz_payment_deadline');
         $complated_date = date('Y-m-d');
     }
     //Account & Invoice settings
     $beallitasok = $szamla->addChild('beallitasok');
     $beallitasok->addChild('felhasznalo', get_option('wc_szamlazz_username'));
     $beallitasok->addChild('jelszo', get_option('wc_szamlazz_password'));
     if (get_option('wc_szamlazz_invoice_type') != 'paper') {
         $beallitasok->addChild('eszamla', 'true');
     } else {
         $beallitasok->addChild('eszamla', 'false');
     }
     $beallitasok->addChild('szamlaLetoltes', 'true');
     //Invoice details
     $fejlec = $szamla->addChild('fejlec');
     $fejlec->addChild('keltDatum', date('Y-m-d'));
     $fejlec->addChild('teljesitesDatum', $complated_date);
     if ($deadline) {
         $fejlec->addChild('fizetesiHataridoDatum', date('Y-m-d', strtotime('+' . $deadline . ' days')));
     } else {
         $fejlec->addChild('fizetesiHataridoDatum', date('Y-m-d'));
     }
     $fejlec->addChild('fizmod', $order->payment_method_title);
     $fejlec->addChild('penznem', $order->get_order_currency());
     $fejlec->addChild('szamlaNyelve', 'hu');
     $fejlec->addChild('megjegyzes', $note);
     if ($order->get_order_currency() != 'HUF') {
         //if the base currency is not HUF, we should define currency rates
         $fejlec->addChild('arfolyamBank', '');
         $fejlec->addChild('arfolyam', 0);
     }
     $fejlec->addChild('rendelesSzam', $order->get_order_number());
     $fejlec->addChild('elolegszamla', 'false');
     $fejlec->addChild('vegszamla', 'false');
     //Seller details
     $elado = $szamla->addChild('elado');
     //Customer details
     $vevo = $szamla->addChild('vevo');
     $vevo->addChild('nev', ($order->billing_company ? $order->billing_company . ' - ' : '') . $order->billing_first_name . ' ' . $order->billing_last_name);
     $vevo->addChild('irsz', $order->billing_postcode);
     $vevo->addChild('telepules', $order->billing_city);
     $vevo->addChild('cim', $order->billing_address_1);
     $vevo->addChild('email', $order->billing_email);
     $vevo->addChild('adoszam', '');
     $vevo->addChild('telefonszam', $order->billing_phone);
     //Customer Shipping details if needed
     if ($order->shipping_address) {
         $vevo->addChild('postazasiNev', ($order->shipping_company ? $order->shipping_company . ' - ' : '') . $order->shipping_first_name . ' ' . $order->shipping_last_name);
         $vevo->addChild('postazasiIrsz', $order->shipping_postcode);
         $vevo->addChild('postazasiTelepules', $order->shipping_city);
         $vevo->addChild('postazasiCim', $order->shipping_address_1);
     }
     //Order Items
     $tetelek = $szamla->addChild('tetelek');
     foreach ($order_items as $termek) {
         $tetel = $tetelek->addChild('tetel');
         $tetel->addChild('megnevezes', htmlspecialchars($termek["name"]));
         $tetel->addChild('mennyiseg', $termek["qty"]);
         $tetel->addChild('mennyisegiEgyseg', '');
         $tetel->addChild('nettoEgysegar', round($termek["line_total"], 2) / $termek["qty"]);
         $tetel->addChild('afakulcs', round($termek["line_tax"] / $termek["line_total"] * 100));
         $tetel->addChild('nettoErtek', round($termek["line_total"], 2));
         $tetel->addChild('afaErtek', round($termek["line_tax"], 2));
         $tetel->addChild('bruttoErtek', round($termek["line_total"], 2) + round($termek["line_tax"], 2));
         $tetel->addChild('megjegyzes', '');
     }
     //Shipping
     if ($order->get_shipping_methods()) {
         $tetel = $tetelek->addChild('tetel');
         $tetel->addChild('megnevezes', htmlspecialchars($order->get_shipping_method()));
         $tetel->addChild('mennyiseg', '1');
         $tetel->addChild('mennyisegiEgyseg', '');
         $tetel->addChild('nettoEgysegar', round($order->order_shipping, 2));
         if ($order->order_shipping == 0) {
             $tetel->addChild('afakulcs', '0');
         } else {
             $tetel->addChild('afakulcs', round($order->order_shipping_tax / $order->order_shipping * 100));
         }
         $tetel->addChild('nettoErtek', round($order->order_shipping, 2));
         $tetel->addChild('afaErtek', round($order->order_shipping_tax, 2));
         $tetel->addChild('bruttoErtek', round($order->order_shipping, 2) + round($order->order_shipping_tax, 2));
         $tetel->addChild('megjegyzes', '');
     }
     //Extra Fees
     $fees = $order->get_fees();
     if (!empty($fees)) {
         foreach ($fees as $fee) {
             $tetel = $tetelek->addChild('tetel');
             $tetel->addChild('megnevezes', htmlspecialchars($fee["name"]));
             $tetel->addChild('mennyiseg', 1);
             $tetel->addChild('mennyisegiEgyseg', '');
             $tetel->addChild('nettoEgysegar', round($fee["line_total"], 2));
             $tetel->addChild('afakulcs', round($fee["line_tax"] / $fee["line_total"] * 100));
             $tetel->addChild('nettoErtek', round($fee["line_total"], 2));
             $tetel->addChild('afaErtek', round($fee["line_tax"], 2));
             $tetel->addChild('bruttoErtek', round($fee["line_total"], 2) + round($fee["line_tax"], 2));
             $tetel->addChild('megjegyzes', '');
         }
     }
     //Discount
     if ($order->order_discount > 0) {
         $tetel = $tetelek->addChild('tetel');
         $tetel->addChild('megnevezes', 'Kedvezmény');
         $tetel->addChild('mennyiseg', '1');
         $tetel->addChild('mennyisegiEgyseg', '');
         $tetel->addChild('nettoEgysegar', -$order->order_discount);
         $tetel->addChild('afakulcs', 0);
         $tetel->addChild('nettoErtek', -$order->order_discount);
         $tetel->addChild('afaErtek', 0);
         $tetel->addChild('bruttoErtek', -$order->order_discount);
         $tetel->addChild('megjegyzes', '');
     }
     //Generate XML
     $xml_szamla = apply_filters('wc_szamlazz_xml', $szamla, $order);
     $xml = $xml_szamla->asXML();
     //Temporarily save XML
     $UploadDir = wp_upload_dir();
     $UploadURL = $UploadDir['basedir'];
     $location = realpath($UploadURL . "/wc_szamlazz/");
     $xmlfile = $location . '/' . $orderId . '.xml';
     $test = file_put_contents($xmlfile, $xml);
     //Generate cookie
     $cookie_file = $location . '/szamlazz_cookie.txt';
     //Agent URL
     $agent_url = 'https://www.szamlazz.hu/szamla/';
     //Geerate Cookie if not already exists
     if (!file_exists($cookie_file)) {
         file_put_contents($cookie_file, '');
     }
     // a CURL inicializálása
     $ch = curl_init($agent_url);
     // A curl hívás esetén tanúsítványhibát kaphatunk az SSL tanúsítvány valódiságától
     // függetlenül, ez az alábbi CURL paraméter állítással kiküszöbölhető,
     // ilyenkor nincs külön SSL ellenőrzés:
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
     // POST-ban küldjük az adatokat
     curl_setopt($ch, CURLOPT_POST, true);
     // Kérjük a HTTP headert a válaszba, fontos információk vannak benne
     curl_setopt($ch, CURLOPT_HEADER, true);
     // változóban tároljuk a válasz tartalmát, nem írjuk a kimenetbe
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     // Beállítjuk, hol van az XML, amiből számlát szeretnénk csinálni (= file upload)
     // az xmlfile-t itt fullpath-al kell megadni
     if (!class_exists('CurlFile')) {
         curl_setopt($ch, CURLOPT_POSTFIELDS, array('action-xmlagentxmlfile' => '@' . $xmlfile));
     } else {
         curl_setopt($ch, CURLOPT_POSTFIELDS, array('action-xmlagentxmlfile' => new CurlFile($xmlfile)));
     }
     // 30 másodpercig tartjuk fenn a kapcsolatot (ha valami bökkenő volna)
     curl_setopt($ch, CURLOPT_TIMEOUT, 30);
     // Itt állítjuk be, hogy az érkező cookie a $cookie_file-ba kerüljön mentésre
     curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
     // Ha van már cookie file-unk, és van is benne valami, elküldjük a Számlázz.hu-nak
     if (file_exists($cookie_file) && filesize($cookie_file) > 0) {
         curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
     }
     // elküldjük a kérést a Számlázz.hu felé, és eltároljuk a választ
     $agent_response = curl_exec($ch);
     // kiolvassuk a curl-ból volt-e hiba
     $http_error = curl_error($ch);
     // ezekben a változókban tároljuk a szétbontott választ
     $agent_header = '';
     $agent_body = '';
     $agent_http_code = '';
     // lekérjük a válasz HTTP_CODE-ját, ami ha 200, akkor a http kommunikáció rendben volt
     // ettől még egyáltalán nem biztos, hogy a számla elkészült
     $agent_http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
     // a válasz egy byte kupac, ebből az első "header_size" darab byte lesz a header
     $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
     // a header tárolása, ebben lesznek majd a számlaszám, bruttó nettó összegek, errorcode, stb.
     $agent_header = substr($agent_response, 0, $header_size);
     // a body tárolása, ez lesz a pdf, vagy szöveges üzenet
     $agent_body = substr($agent_response, $header_size);
     // a curl már nem kell, lezárjuk
     curl_close($ch);
     // a header soronként tartalmazza az információkat, egy tömbbe teszük a külön sorokat
     $header_array = explode("\n", $agent_header);
     // ezt majd true-ra állítjuk ha volt hiba
     $volt_hiba = false;
     // ebben lesznek a hiba információk, plusz a bodyban
     $agent_error = '';
     $agent_error_code = '';
     // menjünk végig a header sorokon, ami "szlahu"-val kezdődik az érdekes nekünk és írjuk ki
     foreach ($header_array as $val) {
         if (substr($val, 0, strlen('szlahu')) === 'szlahu') {
             // megvizsgáljuk, hogy volt-e hiba
             if (substr($val, 0, strlen('szlahu_error:')) === 'szlahu_error:') {
                 // sajnos volt
                 $volt_hiba = true;
                 $agent_error = substr($val, strlen('szlahu_error:'));
             }
             if (substr($val, 0, strlen('szlahu_error_code:')) === 'szlahu_error_code:') {
                 // sajnos volt
                 $volt_hiba = true;
                 $agent_error_code = substr($val, strlen('szlahu_error_code:'));
             }
         }
     }
     // ha volt http hiba dobunk egy kivételt
     $response = array();
     $response['error'] = false;
     if ($http_error != "") {
         $response['error'] = true;
         $response['messages'][] = 'Http hiba történt:' . $http_error;
         return $response;
     }
     //Delete the XML if not debug mode
     if (!get_option('wc_szamlazz_debug')) {
         unlink($xmlfile);
     } else {
         //Rename XML file for security
         $random_file_name = substr(md5(rand()), 5);
         rename($xmlfile, $location . '/' . $orderId . '-' . $random_file_name . '.xml');
     }
     if ($volt_hiba) {
         $response['error'] = true;
         // ha a számla nem készült el kiírjuk amit lehet
         $response['messages'][] = 'Agent hibakód: ' . $agent_error_code;
         $response['messages'][] = 'Agent hibaüzenet: ' . urldecode($agent_error);
         $response['messages'][] = 'Agent válasz: ' . urldecode($agent_body);
         //Update order notes
         $order->add_order_note(__('Szamlazz.hu számlakészítás sikertelen! Agent hibakód: ', 'wc-szamlazz') . $agent_error_code);
         // dobunk egy kivételt
         return $response;
     } else {
         //Get the Invoice ID from the response header
         $szlahu_szamlaszam = '';
         foreach ($header_array as $val) {
             if (substr($val, 0, strlen('szlahu_szamlaszam')) === 'szlahu_szamlaszam') {
                 $szlahu_szamlaszam = substr($val, strlen('szlahu_szamlaszam:'));
                 break;
             }
         }
         //Build response array
         $response['messages'][] = __('Számla sikeresen létrehozva és elküldve a vásárlónak emailben.', 'wc-szamlazz');
         $response['invoice_name'] = $szlahu_szamlaszam;
         //Store as a custom field
         update_post_meta($orderId, '_wc_szamlazz', $szlahu_szamlaszam);
         //Update order notes
         $order->add_order_note(__('Szamlazz.hu számla sikeresen létrehozva. A számla sorszáma: ', 'wc-szamlazz') . $szlahu_szamlaszam);
         //Download & Store PDF - generate a random file name so it will be downloadable later only by you
         $random_file_name = substr(md5(rand()), 5);
         $pdf_file_name = 'szamla_' . $random_file_name . '_' . $orderId . '.pdf';
         $pdf_file = $location . '/' . $pdf_file_name;
         file_put_contents($pdf_file, $agent_body);
         //Store the filename
         update_post_meta($orderId, '_wc_szamlazz_pdf', $pdf_file_name);
         //Return the download url
         $response['link'] = '<p><a href="' . $this->generate_download_link($orderId) . '" id="wc_szamlazz_download" class="button button-primary" target="_blank">' . __('Számla megtekintése', 'wc-szamlazz') . '</a></p>';
         return $response;
     }
 }
 protected function formOrderArray(\WC_Order $order)
 {
     $totalFees = 0;
     foreach ($order->get_fees() as $fee) {
         $totalFees += $fee['line_total'];
     }
     $this->order = array('order_id' => $order->id, 'revenue' => round($order->order_total - $totalFees, wc_get_price_decimals()), 'shipping' => $order->get_total_shipping(), 'tax' => $order->get_total_tax());
     return $this->order;
 }
 public static function update_service_fee_subtotal_on_order_creation($order_id, $posted)
 {
     $order = new WC_Order($order_id);
     foreach ($order->get_fees() as $oiid => $fee) {
         if (woocommerce_get_order_item_meta($oiid, '_line_subtotal', true) === '') {
             woocommerce_update_order_item_meta($oiid, '_line_subtotal', woocommerce_get_order_item_meta($oiid, '_line_total', true));
         }
     }
 }
 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;
 }
        /**
         * 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>';
        }
 /**
  * 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);
 }
 /**
  * Perform data update
  *
  * @return JSON object with information about number of posts remaining, current update status
  */
 public static function update_post_data()
 {
     global $wpdb;
     // Number of posts to process at once
     $posts_per_page = 10;
     // Index of last processed post
     $last_post = $_POST['last_post'];
     // Page counters
     $total_pages = $last_post == 0 ? 0 : $_POST['total_pages'];
     $current_page = $last_post == 0 ? 1 : $_POST['current_page'];
     // On first run, determine $total_count/$total_pages
     if ($last_post == 0) {
         $total_count = $wpdb->get_var("SELECT COUNT(ID) FROM {$wpdb->posts} WHERE post_type = 'wootax_order'");
         if ($total_count == 0) {
             update_option('wootax_version', WT_VERSION);
             self::dismiss_update_message();
             die(json_encode(array('status' => 'done', 'message' => 'No more posts to update. Redirecting...', 'redirect' => get_admin_url('plugins.php'))));
         }
         $total_pages = ceil($total_count / $posts_per_page);
     }
     // Select posts from index $last_post to $posts_per_page for processing
     $posts = $wpdb->get_results("SELECT p.ID AS WTID, pm.meta_value AS WCID FROM {$wpdb->posts} p LEFT JOIN {$wpdb->postmeta} pm ON pm.post_id = p.ID WHERE p.post_type = 'wootax_order' AND pm.meta_key = '_wootax_wc_order_id' ORDER BY p.ID ASC LIMIT {$last_post}, {$posts_per_page}");
     if (count($posts) == 0) {
         update_option('wootax_version', WT_VERSION);
         self::dismiss_update_message();
         self::remove_order_posts();
         die(json_encode(array('status' => 'done', 'message' => 'No more posts to update. Redirecting...', 'redirect' => get_admin_url('plugins.php'))));
     }
     // Loop through posts and update
     foreach ($posts as $post) {
         $wt_order_id = $post->WTID;
         $wc_order_id = $post->WCID;
         // Transfer meta that doesn't need to be changed
         $direct_meta_keys = array('tax_total', 'shipping_tax_total', 'captured', 'refunded', 'customer_id', 'tax_item_id', 'exemption_applied');
         foreach ($direct_meta_keys as $key) {
             update_post_meta($wc_order_id, '_wootax_' . $key, get_post_meta($wt_order_id, '_wootax_' . $key, true));
         }
         // WooTax order item meta and mapping array structure was changed drastically in 4.2; update accordingly
         $lookup_data = get_post_meta($wt_order_id, '_wootax_lookup_data', true);
         $cart_taxes = get_post_meta($wt_order_id, '_wootax_cart_taxes', true);
         $new_mapping_array = array();
         $new_tc_ids = array();
         $identifiers = array();
         if (is_array($lookup_data)) {
             $wc_order = new WC_Order($wc_order_id);
             $order_items = $wc_order->get_items();
             $order_fees = $wc_order->get_fees();
             foreach ($lookup_data as $location_key => $items) {
                 if (!isset($new_mapping_array[$location_key])) {
                     $new_mapping_array[$location_key] = array();
                 }
                 foreach ($items as $index => $item) {
                     if (!is_array($item)) {
                         continue;
                     }
                     $tax_amount = isset($cart_taxes[$location_key][$index]) ? $cart_taxes[$location_key][$index] : 0;
                     $item_ident = $item['ItemID'];
                     if ($item_ident == 99999) {
                         $shipping_item_id = -1;
                         // Shipping
                         if (version_compare(WOOCOMMERCE_VERSION, '2.2', '<')) {
                             $shipping_item_id = WT_SHIPPING_ITEM;
                             update_post_meta($wc_order_id, '_wootax_first_found', $location_key);
                             update_post_meta($wc_order_id, '_wootax_shipping_index', $index);
                         } else {
                             $shipping_methods = $wc_order->get_items('shipping');
                             foreach ($shipping_methods as $item_id => $method) {
                                 if ($shipping_item_id == -1) {
                                     $shipping_item_id = $item_id;
                                     wc_update_order_item_meta($item_id, '_wootax_index', $index);
                                     wc_update_order_item_meta($item_id, '_wootax_tax_amount', $tax_amount);
                                     wc_update_order_item_meta($item_id, '_wootax_location_id', $location_key);
                                 }
                             }
                         }
                         if ($shipping_item_id != -1) {
                             $new_mapping_array[$location_key][$item_ident] = $index;
                             $identifiers[WT_SHIPPING_ITEM] = $item_ident;
                         }
                     } else {
                         if (in_array(get_post_type($item_ident), array('product', 'product-variation'))) {
                             // Cart item
                             $cart_item_id = -1;
                             if (get_post_type($item_ident) == 'product') {
                                 $product_id = $item_ident;
                                 $variation_id = '';
                             } else {
                                 if (get_post_type($item_ident) == 'product-variation') {
                                     $variation_id = $item_ident;
                                     $product_id = wp_get_post_parent_id($variation_id);
                                 }
                             }
                             foreach ($order_items as $item_id => $item_data) {
                                 if (!empty($item_data['variation_id']) && $item_data['variation_id'] == $variation_id || $item_data['product_id'] == $product_id) {
                                     $cart_item_id = $item_id;
                                     break;
                                 }
                             }
                             if ($cart_item_id != -1) {
                                 wc_update_order_item_meta($cart_item_id, '_wootax_index', $index);
                                 wc_update_order_item_meta($cart_item_id, '_wootax_tax_amount', $tax_amount);
                                 wc_update_order_item_meta($cart_item_id, '_wootax_location_id', $location_key);
                                 $new_mapping_array[$location_key][$item_ident] = $index;
                                 $identifiers[$item_ident] = $item_ident;
                             }
                         } else {
                             // Fee
                             $fee_id = -1;
                             foreach ($order_fees as $item_id => $item_data) {
                                 if (sanitize_title($item_data['name']) == $item_ident) {
                                     $fee_id = $item_id;
                                 }
                             }
                             if ($fee_id != -1) {
                                 wc_update_order_item_meta($fee_id, '_wootax_index', $index);
                                 wc_update_order_item_meta($fee_id, '_wootax_tax_amount', $tax_amount);
                                 wc_update_order_item_meta($fee_id, '_wootax_location_id', $location_key);
                                 $new_mapping_array[$location_key][$item_ident] = $index;
                                 $identifiers[$item_ident] = $item_ident;
                             }
                         }
                     }
                 }
             }
         }
         // Update TaxCloud Ids
         $new_tc_ids[$location_key]['cart_id'] = $items['cart_id'];
         $new_tc_ids[$location_key]['order_id'] = $items['order_id'];
         update_post_meta($wc_order_id, '_wootax_taxcloud_ids', $new_tc_ids);
         // Update mapping array
         update_post_meta($wc_order_id, '_wootax_mapping_array', $new_mapping_array);
         // Update item identifiers
         update_post_meta($wc_order_id, '_wootax_identifiers', $identifiers);
     }
     // Notify client that processing has succeeded and continue processing
     if ($current_page < $total_pages) {
         $last_post += $posts_per_page;
         $current_page++;
     } else {
         $last_post += count($posts);
     }
     die(json_encode(array('status' => 'working', 'last_post' => $last_post, 'current_page' => $current_page, 'total_pages' => $total_pages)));
 }
 /**
  * Get the order data for the given ID.
  *
  * @since  2.5.0
  * @param  WC_Order $order The order instance
  * @return array
  */
 protected function get_order_data($order)
 {
     $order_post = get_post($order->id);
     $dp = wc_get_price_decimals();
     $order_data = array('id' => $order->id, 'order_number' => $order->get_order_number(), 'created_at' => $this->format_datetime($order_post->post_date_gmt), 'updated_at' => $this->format_datetime($order_post->post_modified_gmt), 'completed_at' => $this->format_datetime($order->completed_date, true), 'status' => $order->get_status(), 'currency' => $order->get_order_currency(), 'total' => wc_format_decimal($order->get_total(), $dp), 'subtotal' => wc_format_decimal($order->get_subtotal(), $dp), 'total_line_items_quantity' => $order->get_item_count(), 'total_tax' => wc_format_decimal($order->get_total_tax(), $dp), 'total_shipping' => wc_format_decimal($order->get_total_shipping(), $dp), 'cart_tax' => wc_format_decimal($order->get_cart_tax(), $dp), 'shipping_tax' => wc_format_decimal($order->get_shipping_tax(), $dp), 'total_discount' => wc_format_decimal($order->get_total_discount(), $dp), 'shipping_methods' => $order->get_shipping_method(), 'payment_details' => array('method_id' => $order->payment_method, 'method_title' => $order->payment_method_title, 'paid' => isset($order->paid_date)), 'billing_address' => array('first_name' => $order->billing_first_name, 'last_name' => $order->billing_last_name, 'company' => $order->billing_company, 'address_1' => $order->billing_address_1, 'address_2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'postcode' => $order->billing_postcode, 'country' => $order->billing_country, 'email' => $order->billing_email, 'phone' => $order->billing_phone), 'shipping_address' => array('first_name' => $order->shipping_first_name, 'last_name' => $order->shipping_last_name, 'company' => $order->shipping_company, 'address_1' => $order->shipping_address_1, 'address_2' => $order->shipping_address_2, 'city' => $order->shipping_city, 'state' => $order->shipping_state, 'postcode' => $order->shipping_postcode, 'country' => $order->shipping_country), 'note' => $order->customer_note, 'customer_ip' => $order->customer_ip_address, 'customer_user_agent' => $order->customer_user_agent, 'customer_id' => $order->get_user_id(), 'view_order_url' => $order->get_view_order_url(), 'line_items' => array(), 'shipping_lines' => array(), 'tax_lines' => array(), 'fee_lines' => array(), 'coupon_lines' => array());
     // add line items
     foreach ($order->get_items() as $item_id => $item) {
         $product = $order->get_product_from_item($item);
         $product_id = null;
         $product_sku = null;
         // Check if the product exists.
         if (is_object($product)) {
             $product_id = isset($product->variation_id) ? $product->variation_id : $product->id;
             $product_sku = $product->get_sku();
         }
         $meta = new WC_Order_Item_Meta($item, $product);
         $item_meta = array();
         foreach ($meta->get_formatted(null) as $meta_key => $formatted_meta) {
             $item_meta[] = array('key' => $meta_key, 'label' => $formatted_meta['label'], 'value' => $formatted_meta['value']);
         }
         $order_data['line_items'][] = array('id' => $item_id, 'subtotal' => wc_format_decimal($order->get_line_subtotal($item, false, false), $dp), 'subtotal_tax' => wc_format_decimal($item['line_subtotal_tax'], $dp), 'total' => wc_format_decimal($order->get_line_total($item, false, false), $dp), 'total_tax' => wc_format_decimal($item['line_tax'], $dp), 'price' => wc_format_decimal($order->get_item_total($item, false, false), $dp), 'quantity' => wc_stock_amount($item['qty']), 'tax_class' => !empty($item['tax_class']) ? $item['tax_class'] : null, 'name' => $item['name'], 'product_id' => $product_id, 'sku' => $product_sku, 'meta' => $item_meta);
     }
     // Add shipping.
     foreach ($order->get_shipping_methods() as $shipping_item_id => $shipping_item) {
         $order_data['shipping_lines'][] = array('id' => $shipping_item_id, 'method_id' => $shipping_item['method_id'], 'method_title' => $shipping_item['name'], 'total' => wc_format_decimal($shipping_item['cost'], $dp));
     }
     // Add taxes.
     foreach ($order->get_tax_totals() as $tax_code => $tax) {
         $order_data['tax_lines'][] = array('id' => $tax->id, 'rate_id' => $tax->rate_id, 'code' => $tax_code, 'title' => $tax->label, 'total' => wc_format_decimal($tax->amount, $dp), 'compound' => (bool) $tax->is_compound);
     }
     // Add fees.
     foreach ($order->get_fees() as $fee_item_id => $fee_item) {
         $order_data['fee_lines'][] = array('id' => $fee_item_id, 'title' => $fee_item['name'], 'tax_class' => !empty($fee_item['tax_class']) ? $fee_item['tax_class'] : null, 'total' => wc_format_decimal($order->get_line_total($fee_item), $dp), 'total_tax' => wc_format_decimal($order->get_line_tax($fee_item), $dp));
     }
     // Add coupons.
     foreach ($order->get_items('coupon') as $coupon_item_id => $coupon_item) {
         $order_data['coupon_lines'][] = array('id' => $coupon_item_id, 'code' => $coupon_item['name'], 'amount' => wc_format_decimal($coupon_item['discount_amount'], $dp));
     }
     $order_data = apply_filters('woocommerce_cli_order_data', $order_data);
     return $this->flatten_array($order_data);
 }
 /**
  * Get order items.
  *
  * @param  WC_Order $order Order data.
  *
  * @return array           Items list, extra amount and shipping cost.
  */
 protected function get_order_items($order)
 {
     $items = array();
     $extra_amount = 0;
     $shipping_cost = 0;
     // Force only one item.
     if ('yes' == $this->gateway->send_only_total) {
         $items[] = array('description' => $this->sanitize_description(sprintf(__('Order %s', 'woocommerce-pagseguro'), $order->get_order_number())), 'amount' => $this->money_format($order->get_total()), 'quantity' => 1);
     } else {
         // Products.
         if (0 < count($order->get_items())) {
             foreach ($order->get_items() as $order_item) {
                 if ($order_item['qty']) {
                     $item_name = $order_item['name'];
                     if (defined('WC_VERSION') && version_compare(WC_VERSION, '2.4.0', '<')) {
                         $item_meta = new WC_Order_Item_Meta($order_item['item_meta']);
                     } else {
                         $item_meta = new WC_Order_Item_Meta($order_item);
                     }
                     if ($meta = $item_meta->display(true, true)) {
                         $item_name .= ' - ' . $meta;
                     }
                     $items[] = array('description' => $this->sanitize_description($item_name), 'amount' => $this->money_format($order->get_item_total($order_item, false)), 'quantity' => $order_item['qty']);
                 }
             }
         }
         // Fees.
         if (0 < count($order->get_fees())) {
             foreach ($order->get_fees() as $fee) {
                 $items[] = array('description' => $this->sanitize_description($fee['name']), 'amount' => $this->money_format($fee['line_total']), 'quantity' => 1);
             }
         }
         // Taxes.
         if (0 < count($order->get_taxes())) {
             foreach ($order->get_taxes() as $tax) {
                 $items[] = array('description' => $this->sanitize_description($tax['label']), 'amount' => $this->money_format($tax['tax_amount'] + $tax['shipping_tax_amount']), 'quantity' => 1);
             }
         }
         // Shipping Cost.
         if (0 < $order->get_total_shipping()) {
             $shipping_cost = $this->money_format($order->get_total_shipping());
         }
         // Discount.
         if (defined('WC_VERSION') && version_compare(WC_VERSION, '2.3', '<')) {
             if (0 < $order->get_order_discount()) {
                 $extra_amount = '-' . $this->money_format($order->get_order_discount());
             }
         }
     }
     return array('items' => $items, 'extra_amount' => $extra_amount, 'shipping_cost' => $shipping_cost);
 }
Exemple #19
0
 function charge_payment($order_id)
 {
     global $woocommerce;
     $order_items = array();
     $order = new WC_Order($order_id);
     MEOWallet_Config::$isProduction = $this->environment == 'production' ? TRUE : FALSE;
     MEOWallet_Config::$apikey = MEOWallet_Config::$isProduction ? $this->apikey_live : $this->apikey_sandbox;
     //MEOWallet_Config::$isTuned = 'yes';
     $params = array('payment' => array('client' => array('name' => $order->billing_first_name . ' ' . $order->billing_last_name, 'email' => $_POST['billing_email'], 'address' => array('country' => $_POST['billing_country'], 'address' => $_POST['billing_address_1'], 'city' => $_POST['billing_city'], 'postalcode' => $_POST['billing_postcode'])), 'amount' => $order->get_total(), 'currency' => 'EUR', 'items' => $items, 'url_confirm' => get_permalink(woocommerce_get_page_id('shop')) . '?' . $post_result_array->id, 'url_cancel' => get_permalink(woocommerce_get_page_id('shop')) . '?' . $post_result_array->id));
     $client_details = array();
     $client_details['name'] = $_POST['billing_first_name'] . ' ' . $_POST['billing_last_name'];
     $client_details['email'] = $_POST['billing_email'];
     //$client_details['address'] = $client_address;
     $client_address = array();
     $client_address['country'] = $_POST['billing_country'];
     $client_address['address'] = $_POST['billing_address_1'];
     $client_address['city'] = $_POST['billing_city'];
     $client_address['postalcode'] = $_POST['billing_postcode'];
     //$params['payment']['client'] = $client_details;
     //$params['payment']['client']['address'] = $client_address;
     $items = array();
     if (sizeof($order->get_items()) > 0) {
         foreach ($order->get_items() as $item) {
             if ($item['qty']) {
                 $product = $order->get_product_from_item($item);
                 $client_items = array();
                 $client_items['client']['id'] = $item['id'];
                 $client_item['client']['name'] = $item['name'];
                 $client_items['client']['description'] = $item['name'];
                 $client_item['client']['qt'] = $item['qty'];
                 $items['client'][] = $client_items;
             }
         }
     }
     if ($order->get_total_shipping() > 0) {
         $items[] = array('id' => 'shippingfee', 'price' => $order->get_total_shipping(), 'quantity' => 1, 'name' => 'Shipping Fee');
     }
     if ($order->get_total_tax() > 0) {
         $items[] = array('id' => 'taxfee', 'price' => $order->get_total_tax(), 'quantity' => 1, 'name' => 'Tax');
     }
     if ($order->get_order_discount() > 0) {
         $items[] = array('id' => 'totaldiscount', 'price' => $order->get_total_discount() * -1, 'quantity' => 1, 'name' => 'Total Discount');
     }
     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++;
         }
     }
     //$params['client']['amount'] = $order->get_total();
     //if (get_woocommerce_currency() != 'EUR'){
     //	foreach ($items as &$item){
     //		$item['price'] = $item['price'] * $this->to_euro_rate;
     //	}
     //	unset($item);
     //	$params['payment']['amount'] *= $this->to_euro_rate;
     //}
     //$params['payment']['items'] = $items;
     //$woocommerce->cart->empty_cart();
     return MEOWallet_Checkout::getRedirectionUrl($params);
 }
 /**
  * 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()));
     }
 }