/** * Returns the shipping total, in order currency. * * @since WooCommerce 2.1. */ public function get_total_shipping() { // If parent has this method, let's use it. It means we are in WooCommerce 2.1+ if (method_exists(get_parent_class($this), __FUNCTION__)) { return parent::get_total_shipping(); } // Fall back to legacy method in WooCommerce 2.0 and earlier return $this->get_shipping(); }
/** * @param WC_Order $order * * @return array */ public static function get_shipping_info($order) { $total = $order->get_total_shipping(); if ($total) { $tax_rate = 100 * $order->order_shipping_tax / $total; } else { $tax_rate = 0; } $serializer = array_merge(self::get_address($order, 'shipping'), array('price' => Aplazame_Filters::decimals($total), 'tax_rate' => Aplazame_Filters::decimals($tax_rate), 'name' => $order->get_shipping_method())); return $serializer; }
/** * Get Komoju Args for passing to Komoju hosted page * * @param WC_Order $order * @return array */ protected function get_komoju_args($order, $method) { WC_Gateway_Komoju::log('Generating payment form for order ' . $order->get_order_number() . '. Notify URL: ' . $this->notify_url); $params = array("transaction[amount]" => $order->get_subtotal() + $order->get_total_shipping(), "transaction[currency]" => get_woocommerce_currency(), "transaction[customer][email]" => $order->billing_email, "transaction[customer][phone]" => $order->billing_phone, "transaction[customer][given_name]" => $order->billing_first_name, "transaction[customer][family_name]" => $order->billing_last_name, "transaction[external_order_num]" => $this->gateway->get_option('invoice_prefix') . $order->get_order_number() . '-' . $this->request_id, "transaction[return_url]" => $this->gateway->get_return_url($order), "transaction[cancel_url]" => $order->get_cancel_order_url_raw(), "transaction[callback_url]" => $this->notify_url, "transaction[tax]" => strlen($order->get_total_tax()) == 0 ? 0 : $order->get_total_tax(), "timestamp" => time()); WC_Gateway_Komoju::log('Raw parametres: ' . print_r($params, true)); $qs_params = array(); foreach ($params as $key => $val) { $qs_params[] = urlencode($key) . '=' . urlencode($val); } sort($qs_params); $query_string = implode('&', $qs_params); $url = $this->Komoju_endpoint . $method . '/new' . '?' . $query_string; $hmac = hash_hmac('sha256', $url, $this->gateway->secretKey); $query_string .= '&hmac=' . $hmac; return $query_string; }
/** * Bundle and format the order information * @param WC_Order $order * Send as much information about the order as possible to Conekta */ function getRequestData($order) { if ($order and $order != null) { // custom fields $custom_fields = array("total_discount" => (double) $order->get_total_discount() * 100); // $user_id = $order->get_user_id(); // $is_paying_customer = false; $order_coupons = $order->get_used_coupons(); // if ($user_id != 0) { // $custom_fields = array_merge($custom_fields, array( // "is_paying_customer" => is_paying_customer($user_id) // )); // } if (count($order_coupons) > 0) { $custom_fields = array_merge($custom_fields, array("coupon_code" => $order_coupons[0])); } return array("amount" => (double) $order->get_total() * 100, "token" => $_POST['conektaToken'], "shipping_method" => $order->get_shipping_method(), "shipping_carrier" => $order->get_shipping_method(), "shipping_cost" => (double) $order->get_total_shipping() * 100, "monthly_installments" => (int) $_POST['monthly_installments'], "currency" => strtolower(get_woocommerce_currency()), "description" => sprintf("Charge for %s", $order->billing_email), "card" => array_merge(array("name" => sprintf("%s %s", $order->billing_first_name, $order->billing_last_name), "address_line1" => $order->billing_address_1, "address_line2" => $order->billing_address_2, "billing_company" => $order->billing_company, "phone" => $order->billing_phone, "email" => $order->billing_email, "address_city" => $order->billing_city, "address_zip" => $order->billing_postcode, "address_state" => $order->billing_state, "address_country" => $order->billing_country, "shipping_address_line1" => $order->shipping_address_1, "shipping_address_line2" => $order->shipping_address_2, "shipping_phone" => $order->shipping_phone, "shipping_email" => $order->shipping_email, "shipping_address_city" => $order->shipping_city, "shipping_address_zip" => $order->shipping_postcode, "shipping_address_state" => $order->shipping_state, "shipping_address_country" => $order->shipping_country), $custom_fields)); } return false; }
/** * Insert a order in sync table once a order is created * * @global object $wpdb * @param int $order_id * @since 2.4 */ function dokan_sync_order_table($order_id) { global $wpdb; $order = new WC_Order($order_id); $seller_id = dokan_get_seller_id_by_order($order_id); $percentage = dokan_get_seller_percentage($seller_id); //Total calculation $order_total = $order->get_total(); if ($total_refunded = $order->get_total_refunded()) { $order_total = $order_total - $total_refunded; } //Shipping calculation $order_shipping = $order->get_total_shipping(); foreach ($order->get_items() as $item) { $total_shipping_refunded = 0; if ($shipping_refunded = $order->get_total_refunded_for_item($item['product_id'], 'shipping')) { $total_shipping_refunded += $shipping_refunded; } } $order_shipping = $order_shipping - $total_shipping_refunded; //Tax calculation $order_tax = $order->get_total_tax(); if ($tax_refunded = $order->get_total_tax_refunded()) { $order_tax = $order_tax - $tax_refunded; } $extra_cost = $order_shipping + $order_tax; $order_cost = $order_total - $extra_cost; $order_status = $order->post_status; $net_amount = $order_cost * $percentage / 100 + $extra_cost; $net_amount = apply_filters('dokan_sync_order_net_amount', $net_amount, $order); $wpdb->insert($wpdb->prefix . 'dokan_orders', array('order_id' => $order_id, 'seller_id' => $seller_id, 'order_total' => $order_total, 'net_amount' => $net_amount, 'order_status' => $order_status), array('%d', '%d', '%f', '%f', '%s')); }
$product_id = $item['product_id']; $term_list = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids')); $cat_id = (int) $term_list[0]; $category = get_term($cat_id, 'product_cat'); $items[$i]['name'] = $item['name']; $items[$i]['quantity'] = $item['qty']; $items[$i]['sku'] = $product->get_sku(); $items[$i]['price'] = $product->get_price(); $items[$i]['category'] = $category->name; $product_variation_id = $item['variation_id']; // etc $i++; } $amount = $order->get_total(); $affliation = 'Order ' . $order_id . ' details'; $order_shipping_total = $order->get_total_shipping(); $order_cart_tax = $order->get_cart_tax(); //echo '<pre>'; print_r($order); // Transaction Data $trans = array('id' => $order_id, 'affiliation' => $affliation, 'revenue' => $amount, 'shipping' => $order_shipping_total, 'tax' => $order_cart_tax); // Function to return the JavaScript representation of a TransactionData object. function getTransactionJs(&$trans) { return <<<HTML ga('ecommerce:addTransaction', { 'id': '{$trans['id']}', 'affiliation': '{$trans['affiliation']}', 'revenue': '{$trans['revenue']}', 'shipping': '{$trans['shipping']}', 'tax': '{$trans['tax']}' });
/** * 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); }
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); }
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; }
/** * 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); }
public function process_refund($order_id, $amount = NULL, $reason = '') { global $woocommerce; $wc_order = new WC_Order($order_id); $trx_id = get_post_meta($order_id, '_transaction_id', true); $trx_metas = get_post_meta($order_id, '_' . $order_id . '_' . $trx_id . '_metas', true); $last_four = isset($trx_metas['account_number']) ? esc_attr($trx_metas['account_number']) : ''; $refund = new AuthorizeNetAIM(); $customer = (object) array(); $customer->first_name = $wc_order->billing_first_name; $customer->last_name = $wc_order->billing_last_name; $customer->company = $wc_order->billing_company; $customer->address = $wc_order->billing_address_1 . ' ' . $wc_order->billing_address_2; $customer->city = $wc_order->billing_city; $customer->state = $wc_order->billing_state; $customer->zip = $wc_order->billing_postcode; $customer->country = $wc_order->billing_country; $customer->phone = $wc_order->billing_phone; $customer->email = $wc_order->billing_email; $customer->cust_id = $wc_order->user_id; $customer->invoice_num = $wc_order->get_order_number(); $customer->description = get_bloginfo('blogname') . ' Order #' . $wc_order->get_order_number(); $customer->ship_to_first_name = $wc_order->shipping_first_name; $customer->ship_to_last_name = $wc_order->shipping_last_name; $customer->ship_to_company = $wc_order->shipping_company; $customer->ship_to_address = $wc_order->shipping_address_1 . ' ' . $wc_order->shipping_address_2; $customer->ship_to_city = $wc_order->shipping_city; $customer->ship_to_state = $wc_order->shipping_state; $customer->ship_to_zip = $wc_order->shipping_postcode; $customer->ship_to_country = $wc_order->shipping_country; $customer->delim_char = '|'; $customer->encap_char = ''; $customer->customer_ip = $this->get_client_ip(); $customer->tax = $wc_order->get_total_tax(); $customer->freight = $wc_order->get_total_shipping(); $customer->header_email_receipt = 'Refund From ' . get_bloginfo('blogname') . ' ' . $reason; $customer->footer_email_receipt = 'Thank you for Using ' . get_bloginfo('blogname'); $refund->setFields($customer); $refundtrx = $refund->credit($trx_id, $amount, $last_four); if (1 == $refundtrx->approved) { $wc_order->add_order_note(__($refundtrx->response_reason_text . 'on' . date("d-m-Y h:i:s e") . 'with Transaction ID = ' . $refundtrx->transaction_id . ' using ' . strtoupper($refundtrx->transaction_type) . ' and authorization code ' . $refundtrx->authorization_code, 'woocommerce')); if ($wc_order->order_total == $amount) { $wc_order->update_status('wc-refunded'); } return true; } else { if (2 == $refundtrx->response_subcode || 54 == $refundtrx->response_reason_code) { $refundtrx = $refund->void($trx_id); if (1 == $refundtrx->approved) { $wc_order->add_order_note(__($refundtrx->response_reason_text . 'on ' . date("d-m-Y h:i:s e") . 'with Transaction ID = ' . $refundtrx->transaction_id . ' using ' . strtoupper($refundtrx->transaction_type) . ' and authorization code ' . $refundtrx->authorization_code, 'woocommerce')); $wc_order->update_status('wc-cancelled'); return true; } else { $wc_order->add_order_note(__($refundtrx->response_reason_text . '--' . $refundtrx->error_message . ' on ' . date("d-m-Y h:i:s e") . ' using ' . strtoupper($refundtrx->transaction_type), 'woocommerce')); return false; } } else { $wc_order->add_order_note(__($refundtrx->response_reason_text . '--' . $refundtrx->error_message . ' on ' . date("d-m-Y h:i:s e") . ' using ' . strtoupper($refundtrx->transaction_type), 'woocommerce')); return false; } return false; } return false; }
public function WooCommerceProcessTransaction($order_id) { //affiliates manager code WPAM_Logger::log_debug('WooCommerce Integration - Order processed. Order ID: ' . $order_id); if (wpam_has_purchase_record($order_id)) { WPAM_Logger::log_debug('WooCommerce Integration - Affiliate commission for this transaction was awarded once. No need to process anything.'); return; } WPAM_Logger::log_debug('WooCommerce Integration - Checking if affiliate commission needs to be awarded.'); $order = new WC_Order($order_id); $recurring_payment_method = get_post_meta($order_id, '_recurring_payment_method', true); if (!empty($recurring_payment_method)) { WPAM_Logger::log_debug("WooCommerce Integration - This is a recurring payment order. Subscription payment method: " . $recurring_payment_method); WPAM_Logger::log_debug("The commission will be calculated via the recurring payemnt api call."); return; } $order_status = $order->status; WPAM_Logger::log_debug("WooCommerce Integration - Order status: " . $order_status); if (strtolower($order_status) != "completed" && strtolower($order_status) != "processing") { WPAM_Logger::log_debug("WooCommerce Integration - Order status for this transaction is not in a 'completed' or 'processing' state. Commission will not be awarded at this stage."); WPAM_Logger::log_debug("WooCommerce Integration - Commission for this transaciton will be awarded when you set the order status to completed or processing."); return; } $total = $order->order_total; $shipping = $order->get_total_shipping(); $tax = $order->get_total_tax(); WPAM_Logger::log_debug('WooCommerce Integration - Total amount: ' . $total . ', Total shipping: ' . $shipping . ', Total tax: ' . $tax); $purchaseAmount = $total - $shipping - $tax; $wpam_refkey = get_post_meta($order_id, '_wpam_refkey', true); $wpam_id = get_post_meta($order_id, '_wpam_id', true); if (!empty($wpam_id)) { $wpam_refkey = $wpam_id; } $wpam_refkey = apply_filters('wpam_woo_override_refkey', $wpam_refkey, $order); if (empty($wpam_refkey)) { WPAM_Logger::log_debug("WooCommerce Integration - could not get wpam_id/wpam_refkey from cookie. This is not an affiliate sale"); return; } $requestTracker = new WPAM_Tracking_RequestTracker(); WPAM_Logger::log_debug('WooCommerce Integration - awarding commission for order ID: ' . $order_id . '. Purchase amount: ' . $purchaseAmount); $requestTracker->handleCheckoutWithRefKey($order_id, $purchaseAmount, $wpam_refkey); }
/** * Google Analytics eCommerce tracking * * @access public * @param mixed $order_id * @return void */ function ecommerce_tracking_code($order_id) { global $woocommerce; if ($this->disable_tracking($this->ga_eeT) || current_user_can("manage_options") || get_post_meta($order_id, "_tracked", true) == 1) { return; } $tracking_id = $this->ga_id; if (!$tracking_id) { return; } // Doing eCommerce tracking so unhook standard tracking from the footer remove_action("wp_footer", array($this, "ee_settings")); // Get the order and output tracking code $order = new WC_Order($order_id); //Get Applied Coupon Codes $coupons_list = ''; if ($order->get_used_coupons()) { $coupons_count = count($order->get_used_coupons()); $i = 1; foreach ($order->get_used_coupons() as $coupon) { $coupons_list .= $coupon; if ($i < $coupons_count) { $coupons_list .= ', '; } $i++; } } //get domain name if value is set if (!empty($this->ga_Dname)) { $set_domain_name = esc_js($this->ga_Dname); } else { $set_domain_name = "auto"; } //add display features if ($this->ga_DF) { $ga_display_feature_code = 'ga("require", "displayfeatures");'; } else { $ga_display_feature_code = ""; } //add Pageview on order page if user checked Add Standard UA code if ($this->ga_ST) { $ga_pageview = 'ga("send", "pageview");'; } else { $ga_pageview = ""; } $code = '(function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,"script","//www.google-analytics.com/analytics.js","ga"); ga("create", "' . esc_js($tracking_id) . '", "' . $set_domain_name . '"); ' . $ga_display_feature_code . ' ga("require", "ec", "ec.js"); ' . $ga_pageview . ' '; // Order items if ($order->get_items()) { foreach ($order->get_items() as $item) { $_product = $order->get_product_from_item($item); if (isset($_product->variation_data)) { $categories = esc_js(woocommerce_get_formatted_variation($_product->variation_data, true)); } else { $out = array(); $categories = get_the_terms($_product->id, "product_cat"); if ($categories) { foreach ($categories as $category) { $out[] = $category->name; } } $categories = esc_js(join(",", $out)); } //orderpage Prod json $orderpage_prod_Array[get_permalink($_product->id)] = array("tvc_id" => esc_html($_product->id), "tvc_i" => esc_js($_product->get_sku() ? $_product->get_sku() : $_product->id), "tvc_n" => esc_js($item["name"]), "tvc_p" => esc_js($order->get_item_total($item)), "tvc_c" => $categories, "tvc_q" => esc_js($item["qty"])); } //make json for prod meta data on order page $this->wc_version_compare("tvc_oc=" . json_encode($orderpage_prod_Array) . ";"); } //get shipping cost based on version >2.1 get_total_shipping() < get_shipping if (version_compare($woocommerce->version, "2.1", ">=")) { $tvc_sc = $order->get_total_shipping(); } else { $tvc_sc = $order->get_shipping(); } //orderpage transcation data json $orderpage_trans_Array = array("id" => esc_js($order->get_order_number()), "affiliation" => esc_js(get_bloginfo('name')), "revenue" => esc_js($order->get_total()), "tax" => esc_js($order->get_total_tax()), "shipping" => esc_js($tvc_sc), "coupon" => $coupons_list); //make json for trans data on order page $this->wc_version_compare("tvc_td=" . json_encode($orderpage_trans_Array) . ";"); $code .= ' //set local currencies ga("set", "&cu", tvc_lc); for(var t_item in tvc_oc){ ga("ec:addProduct", { "id": tvc_oc[t_item].tvc_i, "name": tvc_oc[t_item].tvc_n, "category": tvc_oc[t_item].tvc_c, "price": tvc_oc[t_item].tvc_p, "quantity": tvc_oc[t_item].tvc_q, }); } ga("ec:setAction","purchase", { "id": tvc_td.id, "affiliation": tvc_td.affiliation, "revenue": tvc_td.revenue, "tax": tvc_td.tax, "shipping": tvc_td.shipping, "coupon": tvc_td.coupon }); ga("send", "event", "Enhanced-Ecommerce","load", "order_confirmation", {"nonInteraction": 1}); '; //check woocommerce version $this->wc_version_compare($code); update_post_meta($order_id, "_tracked", 1); }
/** * Process the payment and return the result * * @access public * @param int $order_id * @return array */ public function process_payment($order_id) { $this->init_mijireh(); $mj_order = new Mijireh_Order(); $wc_order = new WC_Order($order_id); // add items to order $items = $wc_order->get_items(); foreach ($items as $item) { $product = $wc_order->get_product_from_item($item); if (get_option('woocommerce_prices_include_tax') == 'yes') { $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, true, false), $item['qty'], $product->get_sku()); } else { $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, false, true), $item['qty'], $product->get_sku()); } } // Handle fees $items = $wc_order->get_fees(); foreach ($items as $item) { $mj_order->add_item($item['name'], number_format($item['line_total'], 2, '.', ','), 1, ''); } // add billing address to order $billing = new Mijireh_Address(); $billing->first_name = $wc_order->billing_first_name; $billing->last_name = $wc_order->billing_last_name; $billing->street = $wc_order->billing_address_1; $billing->apt_suite = $wc_order->billing_address_2; $billing->city = $wc_order->billing_city; $billing->state_province = $wc_order->billing_state; $billing->zip_code = $wc_order->billing_postcode; $billing->country = $wc_order->billing_country; $billing->company = $wc_order->billing_company; $billing->phone = $wc_order->billing_phone; if ($billing->validate()) { $mj_order->set_billing_address($billing); } // add shipping address to order $shipping = new Mijireh_Address(); $shipping->first_name = $wc_order->shipping_first_name; $shipping->last_name = $wc_order->shipping_last_name; $shipping->street = $wc_order->shipping_address_1; $shipping->apt_suite = $wc_order->shipping_address_2; $shipping->city = $wc_order->shipping_city; $shipping->state_province = $wc_order->shipping_state; $shipping->zip_code = $wc_order->shipping_postcode; $shipping->country = $wc_order->shipping_country; $shipping->company = $wc_order->shipping_company; if ($shipping->validate()) { $mj_order->set_shipping_address($shipping); } // set order name $mj_order->first_name = $wc_order->billing_first_name; $mj_order->last_name = $wc_order->billing_last_name; $mj_order->email = $wc_order->billing_email; // set order totals $mj_order->total = $wc_order->get_total(); $mj_order->discount = $wc_order->get_total_discount(); if (get_option('woocommerce_prices_include_tax') == 'yes') { $mj_order->shipping = round($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2); $mj_order->show_tax = false; } else { $mj_order->shipping = round($wc_order->get_total_shipping(), 2); $mj_order->tax = $wc_order->get_total_tax(); } // add meta data to identify woocommerce order $mj_order->add_meta_data('wc_order_id', $order_id); // Set URL for mijireh payment notificatoin - use WC API $mj_order->return_url = str_replace('https:', 'http:', add_query_arg('wc-api', 'WC_Gateway_Mijireh', home_url('/'))); // Identify woocommerce $mj_order->partner_id = 'woo'; try { $mj_order->create(); $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url); return $result; } catch (Mijireh_Exception $e) { wc_add_notice(__('Mijireh error:', 'woocommerce') . $e->getMessage(), 'error'); } }
/** * Returns the total shipping cost for the given order * * @since 2.0 * @param WC_Order $order * @return float the shipping total */ public static function get_total_shipping($order) { if (self::is_wc_version_gte_2_1()) { return $order->get_total_shipping(); } else { return $order->get_shipping(); } }
/** * Beeptify checkout form */ public function generate_beeptify_form($order_id) { global $woocommerce; $order = new WC_Order($order_id); /* Setup known values */ $amount_total = $order->order_total * 100; $order_number = str_replace('#', null, $order->get_order_number()); $order_id = $order_number; // Shop URL's $decline_url = $woocommerce->cart->get_checkout_url(); //$woocommerce->api_request_url("WC_payment_gateway_beeptify"); $callback_url = add_query_arg('wooorderid', $order_id, WC()->api_request_url('WC_payment_gateway_beeptify')); /* Sale lines */ $SaleLines = array(); /* Make purchase line for display at beeptify */ $reason = get_bloginfo('name') . " sale"; $i = 0; foreach ($woocommerce->cart->get_cart() as $cart_item_key => $cart_item) { $this_product = apply_filters('woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key); $this_product_id = apply_filters('woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key); $this_product_name = $this_product->get_title(); $quantities = WC()->cart->get_cart_item_quantities(); $this_quantity = $quantities[$this_product_id]; $this_price = $this_product->price; //$reason .= "$this_product_name: [br] $this_price". get_woocommerce_currency_symbol() ." x $this_quantity [br] Total: " . $this_total ." ". get_woocommerce_currency_symbol(); $SaleLines[$i]['ProductId'] = $this_product_id; $SaleLines[$i]['ProductName'] = $this_product_name; $SaleLines[$i]['ProductDescription'] = ""; $SaleLines[$i]['Quantity'] = $this_quantity; $SaleLines[$i]['PricePerUnit'] = $this_price * 100; $SaleLines[$i]['IsLoad'] = 0; $SaleLines[$i]['CodeList'] = ""; /* Check for load on product */ $bCodes = get_post_meta($this_product_id, '_beeptify_code', false); if (!empty($bCodes[0])) { $SaleLines[$i]['IsLoad'] = 1; $bCodes = explode(',', $bCodes[0]); end($bCodes); $lastKey = key($bCodes); reset($bCodes); foreach ($bCodes as $key => $bCode) { $SaleLines[$i]['CodeList'] .= trim($bCode); if ($key != $lastKey) { $SaleLines[$i]['CodeList'] .= ", "; } } } $i++; } /* Include shipping for sale line */ if ($order->get_total_shipping() > 0) { $SaleLines[$i]['ProductId'] = "x"; $SaleLines[$i]['ProductName'] = "Shipping"; $SaleLines[$i]['ProductDescription'] = ""; $SaleLines[$i]['Quantity'] = 1; $SaleLines[$i]['PricePerUnit'] = $order->get_total_shipping() * 100; $SaleLines[$i]['IsLoad'] = 0; $SaleLines[$i]['CodeList'] = ""; } /* Test for tax, and add as sale line */ $taxes = $order->get_taxes(); $total_for_test = $order->get_total_tax(); if (is_array($taxes) && $total_for_test > 0) { // It seems to land in a random row? foreach ($taxes as $the_tax) { $taxes = $the_tax; } if (!empty($taxes['tax_amount']) && $taxes['tax_amount'] != 0 || !empty($taxes['shipping_tax_amount']) && $taxes['shipping_tax_amount'] != 0) { $i++; $SaleLines[$i]['ProductId'] = "t"; $SaleLines[$i]['ProductName'] = "Tax"; $SaleLines[$i]['ProductDescription'] = ""; $SaleLines[$i]['Quantity'] = 1; $SaleLines[$i]['PricePerUnit'] = $taxes['tax_amount'] * 100 + $taxes['shipping_tax_amount'] * 100; $SaleLines[$i]['IsLoad'] = 0; $SaleLines[$i]['CodeList'] = ""; } } $css = ''; /* if frame,send the CSS */ if ($this->yesnotoint($this->frame)) { $css = plugins_url("css/gateway.beeptify.css", __FILE__); } $beeptify_args = array('_selectHost' => $this->liveurl, 'MsgType' => 'sale', 'MerchantId' => $this->merchant_id, 'Reason' => $reason, 'OrderNumber' => $order_number, 'ProductId' => '21', 'Amount' => $amount_total, 'SuccessUrl' => $callback_url, 'ErrorUrl' => $decline_url, 'CancelUrl' => $decline_url, 'UserType' => "unregistered", 'UserEmail' => $order->billing_email, 'Css' => $css, 'Language' => $this->pay_language, 'Mode' => $this->mode, 'Secret' => $this->secret); $html_form = array(); /* Primary args */ $to_hash = ""; foreach ($beeptify_args as $key => $arg) { if ($key != '_selectHost' && !empty($arg)) { $to_hash .= $arg; } if ($key != 'Secret') { $html_form[] = "<input type='hidden' name='{$key}' value='{$arg}'/>"; } } /* Sale lines */ foreach ($SaleLines as $key => $line) { foreach ($line as $line_name => $line_value) { $to_hash .= $line_value; $html_form[] = "<input type='hidden' name='SaleLines[{$key}].{$line_name}' value='{$line_value}'/>"; } } /* Hash */ $hash = md5($to_hash); $html_form[] = "<input type='hidden' name='MD5Check' value='{$hash}'/>"; // Debugging /* foreach ($html_form as $entity) { echo "<br>" . htmlspecialchars($entity); } die(); */ /* If we are going with an iframe or a redirect */ if ($this->yesnotoint($this->frame)) { return $this->beeptify_iframe($order, $html_form); } else { return $this->beeptify_redirect($order, $html_form); } }
/** * ConfirmPayment * * Finalizes the checkout with PayPal's DoExpressCheckoutPayment API * * @FinalPaymentAmt (double) Final payment amount for the order. */ function ConfirmPayment($FinalPaymentAmt) { /* * Display message to user if session has expired. */ if (sizeof(WC()->cart->get_cart()) == 0) { wc_add_notice(sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage →</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'), "error"); } /* * Check if the PayPal class has already been established. */ if (!class_exists('Angelleye_PayPal')) { require_once 'lib/angelleye/paypal-php-library/includes/paypal.class.php'; } /* * Create PayPal object. */ $PayPalConfig = array('Sandbox' => $this->testmode == 'yes' ? TRUE : FALSE, 'APIUsername' => $this->api_username, 'APIPassword' => $this->api_password, 'APISignature' => $this->api_signature); $PayPal = new Angelleye_PayPal($PayPalConfig); /* * Get data from WooCommerce object */ if (!empty($this->confirm_order_id)) { $order = new WC_Order($this->confirm_order_id); $invoice_number = preg_replace("/[^0-9,.]/", "", $order->get_order_number()); if ($order->customer_note) { $customer_notes = wptexturize($order->customer_note); } $shipping_first_name = $order->shipping_first_name; $shipping_last_name = $order->shipping_last_name; $shipping_address_1 = $order->shipping_address_1; $shipping_address_2 = $order->shipping_address_2; $shipping_city = $order->shipping_city; $shipping_state = $order->shipping_state; $shipping_postcode = $order->shipping_postcode; $shipping_country = $order->shipping_country; } // Prepare request arrays $DECPFields = array('token' => urlencode($this->get_session('TOKEN')), 'payerid' => urlencode($this->get_session('payer_id')), 'returnfmfdetails' => '', 'giftmessage' => $this->get_session('giftmessage'), 'giftreceiptenable' => $this->get_session('giftreceiptenable'), 'giftwrapname' => $this->get_session('giftwrapname'), 'giftwrapamount' => $this->get_session('giftwrapamount'), 'buyermarketingemail' => '', 'surveyquestion' => '', 'surveychoiceselected' => '', 'allowedpaymentmethod' => ''); $Payments = array(); $Payment = array('amt' => number_format($FinalPaymentAmt, 2, '.', ''), 'currencycode' => get_woocommerce_currency(), 'shippingdiscamt' => '', 'insuranceoptionoffered' => '', 'handlingamt' => '', 'desc' => '', 'custom' => '', 'invnum' => $this->invoice_id_prefix . $invoice_number, 'notifyurl' => '', 'shiptoname' => $shipping_first_name . ' ' . $shipping_last_name, 'shiptostreet' => $shipping_address_1, 'shiptostreet2' => $shipping_address_2, 'shiptocity' => $shipping_city, 'shiptostate' => $shipping_state, 'shiptozip' => $shipping_postcode, 'shiptocountrycode' => $shipping_country, 'shiptophonenum' => '', 'notetext' => $this->get_session('customer_notes'), 'allowedpaymentmethod' => '', 'paymentaction' => 'Sale', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '', 'sellerid' => '', 'sellerusername' => '', 'sellerregistrationdate' => '', 'softdescriptor' => ''); $PaymentOrderItems = array(); $ctr = 0; $ITEMAMT = 0; if (sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $values) { $_product = $order->get_product_from_item($values); $qty = absint($values['qty']); $sku = $_product->get_sku(); $values['name'] = html_entity_decode($values['name'], ENT_NOQUOTES, 'UTF-8'); if ($_product->product_type == 'variation') { if (empty($sku)) { $sku = $_product->parent->get_sku(); } $item_meta = new WC_Order_Item_Meta($values['item_meta']); $meta = $item_meta->display(true, true); if (!empty($meta)) { $values['name'] .= " - " . str_replace(", \n", " - ", $meta); } } /* * Set price based on tax option. */ if (get_option('woocommerce_prices_include_tax') == 'yes') { $product_price = $order->get_item_subtotal($values, true, false); } else { $product_price = $order->get_item_subtotal($values, false, true); } $Item = array('name' => $values['name'], 'desc' => '', 'amt' => $product_price, 'number' => $sku, 'qty' => $qty, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => ''); array_push($PaymentOrderItems, $Item); $ITEMAMT += $product_price * $values['qty']; } /** * Add custom Woo cart fees as line items */ foreach (WC()->cart->get_fees() as $fee) { $Item = array('name' => $fee->name, 'desc' => '', 'amt' => number_format($fee->amount, 2, '.', ''), 'number' => $fee->id, 'qty' => 1, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => ''); /** * The gift wrap amount actually has its own parameter in * DECP, so we don't want to include it as one of the line * items. */ if ($Item['number'] != 'gift-wrap') { array_push($PaymentOrderItems, $Item); $ITEMAMT += $fee->amount * $Item['qty']; } $ctr++; } /* * Get discounts */ if ($order->get_cart_discount() > 0) { foreach (WC()->cart->get_coupons('cart') as $code => $coupon) { $Item = array('name' => 'Cart Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', '')); array_push($PaymentOrderItems, $Item); } $ITEMAMT -= $order->get_cart_discount(); } if ($order->get_order_discount() > 0) { foreach (WC()->cart->get_coupons('order') as $code => $coupon) { $Item = array('name' => 'Order Discount', 'number' => $code, 'qty' => '1', 'amt' => '-' . number_format(WC()->cart->coupon_discount_amounts[$code], 2, '.', '')); array_push($PaymentOrderItems, $Item); } $ITEMAMT -= $order->get_order_discount(); } /* * Set shipping and tax values. */ if (get_option('woocommerce_prices_include_tax') == 'yes') { $shipping = $order->get_total_shipping() + $order->get_shipping_tax(); $tax = 0; } else { $shipping = $order->get_total_shipping(); $tax = $order->get_total_tax(); } /* * Now that we have all items and subtotals * we can fill in necessary values. */ $Payment['itemamt'] = number_format($ITEMAMT, 2, '.', ''); // Required if you specify itemized L_AMT fields. Sum of cost of all items in this order. /* * Set tax */ if ($tax > 0) { $Payment['taxamt'] = number_format($tax, 2, '.', ''); // Required if you specify itemized L_TAXAMT fields. Sum of all tax items in this order. } /* * Set shipping */ if ($shipping > 0) { $Payment['shippingamt'] = number_format($shipping, 2, '.', ''); // Total shipping costs for this order. If you specify SHIPPINGAMT you mut also specify a value for ITEMAMT. } } $Payment['order_items'] = $PaymentOrderItems; array_push($Payments, $Payment); $UserSelectedOptions = array('shippingcalculationmode' => '', 'insuranceoptionselected' => '', 'shippingoptionisdefault' => '', 'shippingoptionamount' => '', 'shippingoptionname' => ''); $PayPalRequestData = array('DECPFields' => $DECPFields, 'Payments' => $Payments); // Pass data into class for processing with PayPal and load the response array into $PayPalResult $PayPalResult = $PayPal->DoExpressCheckoutPayment($PayPalRequestData); /* * Log API result */ $this->add_log('Test Mode: ' . $this->testmode); $this->add_log('Endpoint: ' . $this->API_Endpoint); $PayPalRequest = isset($PayPalResult['RAWREQUEST']) ? $PayPalResult['RAWREQUEST'] : ''; $PayPalResponse = isset($PayPalResult['RAWRESPONSE']) ? $PayPalResult['RAWRESPONSE'] : ''; $this->add_log('Request: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalRequest)), true)); $this->add_log('Response: ' . print_r($PayPal->NVPToArray($PayPal->MaskAPIResult($PayPalResponse)), true)); /* * Error handling */ if ($PayPal->APICallSuccessful($PayPalResult['ACK'])) { $this->remove_session('TOKEN'); } /* * Return the class library result array. */ return $PayPalResult; }
function get_payment_xml($order_id) { global $woocommerce; global $product; $order = new WC_Order($order_id); $Secuitems = ''; foreach ($order->get_items() as $item) { $Options = array(); foreach ($item as $Attribute => $Value) { if (!in_array($Attribute, $this->GetStandardProductFields())) { $Options[$Attribute] = $Value; } } $product = new WC_Product($item['product_id']); $Secuitems .= '[' . $item['product_id'] . '|' . $product->get_sku() . '|' . $item['name']; if (!empty($Options)) { foreach ($Options as $Key => $Value) { if ((string) $Key === 'pa_quantity') { $Key = 'Quantity'; } $Secuitems .= ', ' . $Key . ': ' . $Value; } } $Secuitems .= '|' . $this->currency_format($item['line_total'] / $item['qty']) . '|' . $item['qty'] . '|' . $this->currency_format($item['line_total']) . ']'; } $TransactionSubTotal = $this->currency_format($order->get_subtotal()); $TransactionAmount = $this->currency_format($order->get_total()); $expirydate = str_replace(array('/', ' '), '', $_POST['UPG_api-card-expiry']); $cardnumber = str_replace(array(' ', '-'), '', $_POST['UPG_api-card-number']); $cardcv2 = str_replace(array(' ', '-'), '', $_POST['UPG_api-card-cvc']); $xmlContrsuct = '<?xml version ="1.0"?>'; $xmlContrsuct .= '<request>'; $xmlContrsuct .= '<type>transaction</type>'; $xmlContrsuct .= '<authtype>authorise</authtype>'; $xmlContrsuct .= '<authentication>'; $xmlContrsuct .= '<shreference>' . $this->reference . '</shreference>'; $xmlContrsuct .= '<checkcode>' . $this->checkcode . '</checkcode>'; $xmlContrsuct .= '</authentication>'; $xmlContrsuct .= '<transaction>'; //Card details $xmlContrsuct .= '<cardnumber>' . $cardnumber . '</cardnumber>'; $xmlContrsuct .= '<cv2>' . $cardcv2 . '</cv2>'; $xmlContrsuct .= '<cardexpiremonth>' . substr($expirydate, 0, 2) . '</cardexpiremonth>'; $xmlContrsuct .= '<cardexpireyear>' . substr($expirydate, -2) . '</cardexpireyear>'; //Cardholder details $xmlContrsuct .= '<cardholdersname>' . $order->billing_first_name . ' ' . $order->billing_last_name . '</cardholdersname>'; $xmlContrsuct .= '<cardholdersemail>' . $order->billing_email . '</cardholdersemail>'; $xmlContrsuct .= '<cardholderaddr1>' . $order->billing_address_1 . '</cardholderaddr1>'; $xmlContrsuct .= '<cardholderaddr2>' . $order->billing_address_2 . '</cardholderaddr2>'; $xmlContrsuct .= '<cardholdercity>' . $order->billing_city . '</cardholdercity>'; $xmlContrsuct .= '<cardholderstate>' . $order->billing_state . '</cardholderstate>'; $xmlContrsuct .= '<cardholderpostcode>' . $order->billing_postcode . '</cardholderpostcode>'; $xmlContrsuct .= '<cardholdercountry>' . $order->billing_country . '</cardholdercountry>'; $xmlContrsuct .= '<cardholdertelephonenumber>' . $order->billing_phone . '</cardholdertelephonenumber>'; // Order details $xmlContrsuct .= '<orderid>' . $order->id . '</orderid>'; $xmlContrsuct .= '<subtotal>' . $TransactionSubTotal . '</subtotal>'; $xmlContrsuct .= '<transactionamount>' . $TransactionAmount . '</transactionamount>'; $xmlContrsuct .= '<transactioncurrency>' . get_woocommerce_currency() . '</transactioncurrency>'; $xmlContrsuct .= '<transactiondiscount>' . $this->currency_format($order->get_total_discount()) . '</transactiondiscount>'; $xmlContrsuct .= '<transactiontax>' . $this->currency_format($order->get_total_tax()) . '</transactiontax>'; $xmlContrsuct .= '<shippingcharge>' . $this->currency_format($order->get_total_shipping()) . '</shippingcharge>'; $xmlContrsuct .= '<secuitems><![CDATA[' . $Secuitems . ']]></secuitems>'; $xmlContrsuct .= '</transaction>'; $xmlContrsuct .= '</request>'; return $xmlContrsuct; }
/** * Get products data. * * @param WC_Order $order * * @return array */ protected function get_products_data($order) { $i = 1; $data = array(); // Force only one item. if ('yes' == $this->send_only_total || 'yes' == get_option('woocommerce_prices_include_tax')) { $data['cart_' . $i . '_name'] = $this->sanitize_string(sprintf(__('Order %s', 'woocommerce-checkout-cielo'), $order->get_order_number())); // $data['cart_' . $i . '_description'] = ''; $data['cart_' . $i . '_unitprice'] = $this->get_price($order->get_total()) - $this->get_price($order->get_total_shipping()) + $this->get_discount($order); $data['cart_' . $i . '_quantity'] = '1'; $data['cart_' . $i . '_type'] = '1'; // $data['cart_' . $i . '_code'] = ''; $data['cart_' . $i . '_weight'] = '0'; } else { if (0 < sizeof($order->get_items())) { foreach ($order->get_items() as $order_item) { if ($order_item['qty']) { $item_total = $this->get_price($order->get_item_subtotal($order_item, false)); if (0 > $item_total) { continue; } // Get product data. $_product = apply_filters('woocommerce_order_item_product', $order->get_product_from_item($order_item), $order_item); if (defined('WC_VERSION') && version_compare(WC_VERSION, '2.4.0', '<')) { $item_meta = new WC_Order_Item_Meta($order_item['item_meta'], $_product); } else { $item_meta = new WC_Order_Item_Meta($order_item, $_product); } $data['cart_' . $i . '_name'] = $this->sanitize_string($order_item['name']); if ($meta = $item_meta->display(true, true)) { $data['cart_' . $i . '_description'] = $this->sanitize_string($meta, 256); } $data['cart_' . $i . '_unitprice'] = $item_total; $data['cart_' . $i . '_quantity'] = $order_item['qty']; $data['cart_' . $i . '_type'] = '1'; if ($sku = $_product->get_sku()) { $data['cart_' . $i . '_code'] = $sku; } $data['cart_' . $i . '_weight'] = wc_get_weight($_product->get_weight(), 'g'); $i++; } } } // Fees. if (0 < sizeof($order->get_fees())) { foreach ($order->get_fees() as $fee) { $fee_total = $this->get_price($fee['line_total']); if (0 > $fee_total) { continue; } $data['cart_' . $i . '_name'] = $this->sanitize_string($fee['name']); $data['cart_' . $i . '_unitprice'] = $fee_total; $data['cart_' . $i . '_quantity'] = '1'; $data['cart_' . $i . '_type'] = '4'; $i++; } } // Taxes. if (0 < sizeof($order->get_taxes())) { foreach ($order->get_taxes() as $tax) { $tax_total = $this->get_price($tax['tax_amount'] + $tax['shipping_tax_amount']); if (0 > $tax_total) { continue; } $data['cart_' . $i . '_name'] = $this->sanitize_string($tax['label']); $data['cart_' . $i . '_unitprice'] = $tax_total; $data['cart_' . $i . '_quantity'] = '1'; $data['cart_' . $i . '_type'] = '4'; $i++; } } } return $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); }
/** * 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); }
$product_description = "Ingen beskrivning tillgänglig"; } else { //Begränsa längd $product_description = mb_substr($product_description, 0, 149); } $item_price = number_format($order->get_item_total($item, true) * 100, 0, '', ''); $cart[] = array('ArticleNumber' => $reference, 'ArticleName' => strip_tags($item_name), 'Description' => $product_description, 'Quantity' => intval($item['qty'] * 100), 'Price' => (int) $item_price, 'VAT' => intval($item_tax_percentage . '00')); $totalAmount += $item_price * (int) $item['qty']; } // End if qty } // End foreach } // End if sizeof get_items() // We manually calculate the tax percentage here if ($order->get_total_shipping() > 0) { // Calculate tax percentage $shipping_tax_percentage = round($order->get_shipping_tax() / $order->get_total_shipping(), 2) * 100; } else { $shipping_tax_percentage = 00; } $shipping_price = number_format(($order->get_total_shipping() + $order->get_shipping_tax()) * 100, 0, '', ''); $cart[] = array('ArticleNumber' => '999', 'ArticleName' => $order->get_shipping_method(), 'Description' => $order->get_shipping_method(), 'Quantity' => 100, 'Price' => intval($shipping_price), 'VAT' => intval($shipping_tax_percentage . '00')); $totalAmount += $shipping_price; //Create postData $create['MerchantKey'] = $merchantid; $create['Checksum'] = SHA1($totalAmount * 100 . $sharedSecret); $create['Token'] = strtoupper($storedGet['token']); foreach ($cart as $item) { $create['Articles'][] = $item; }
/** * 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'); } }
/** * Adds product properties to analytics.track() when the order is completed successfully. * * @since 1.0.0 * @access public * * @uses func_get_args() Because our abstract class doesn't know how many parameters are passed to each hook * for each different platform, we use func_get_args(). * * @return array Filtered array of name and properties for analytics.track(). */ public function completed_order() { $args = func_get_args(); $track = $args[0]; if (did_action('woocommerce_thankyou')) { $order_number = get_query_var('order-received'); $order = new WC_Order($order_number); /* Because gateways vary wildly in their usage of the status concept, we check for failure rather than success. */ if ('failed' !== $order->status) { $items = $order->get_items(); $products = array(); foreach ($items as $item) { $_product = $order->get_product_from_item($item); $product = array('id' => $item->product_id, 'sku' => $_product->get_sku(), 'name' => $item['name'], 'price' => $item['line_subtotal'], 'quantity' => $item['qty'], 'category' => implode(', ', wp_list_pluck(wc_get_product_terms($item->product_id, 'product_cat'), 'name'))); $products[] = $product; } $track = array('event' => __('Completed Order', 'segment'), 'properties' => array('id' => $order->get_order_number(), 'total' => $order->get_total(), 'revenue' => $order->get_total() - ($order->get_total_shipping() + $order->get_total_tax()), 'shipping' => $order->get_total_shipping(), 'tax' => $order->get_total_tax(), 'products' => $products)); } } return $track; }
<?php add_action('woocommerce_thankyou', function ($order) { $trans = new WC_Order($order); $items = $trans->get_items(); $length = count($items); foreach ($items as $key => $item) { if ($key + 1 < $length) { $cartProducts[$key] = "\n\t\t{\n\t\t'sku': '" . $item['product_id'] . "',\n\t\t'name': '" . $item['name'] . "',\n\t\t'category': '',\n\t\t'price': '" . $item['line_total'] . "',\n\t\t'quantity': '" . $item['qty'] . "'\n\t\t},"; } else { $cartProducts[$key] = "\n\t\t{\n\t\t'sku': '" . $item['product_id'] . "',\n\t\t'name': '" . $item['name'] . "',\n\t\t'category': '',\n\t\t'price': '" . $item['line_total'] . "',\n\t\t'quantity': '" . $item['qty'] . "'\n\t\t}"; } } echo "<script>dataLayer.push({'transactionId': '" . $trans->get_order_number() . "','transactionAffiliation': '','transactionTotal': '" . $trans->get_total() . "','transactionTax': '" . $trans->get_total_tax() . "','transactionShipping': '" . $trans->get_total_shipping() . "','transactionProducts': ["; foreach ($cartProducts as $row) { echo $row; } echo "]});</script>"; });
/** * Insert a order in sync table once a order is created * * @global object $wpdb * @param int $order_id */ function dokan_sync_insert_order($order_id) { global $wpdb; $order = new WC_Order($order_id); $seller_id = dokan_get_seller_id_by_order($order_id); $percentage = dokan_get_seller_percentage($seller_id); $order_total = $order->get_total(); $shipping_total = $order->get_total_shipping(); $cart_total = $order_total - $shipping_total; $order_status = $order->post_status; $wpdb->insert($wpdb->prefix . 'dokan_orders', array('order_id' => $order_id, 'seller_id' => $seller_id, 'order_total' => $order_total, 'net_amount' => $cart_total * $percentage / 100 + $shipping_total, 'order_status' => $order_status), array('%d', '%d', '%f', '%f', '%s')); }
/** * Insert a order in sync table once a order is created * * @global object $wpdb * @param int $order_id */ function dokan_sync_insert_order($order_id) { global $wpdb; $order = new WC_Order($order_id); $seller_id = dokan_get_seller_id_by_order($order_id); $percentage = dokan_get_seller_percentage($seller_id); $order_total = $order->get_total(); $order_shipping = $order->get_total_shipping(); $order_tax = $order->get_total_tax(); $extra_cost = $order_shipping + $order_tax; $order_cost = $order_total - $extra_cost; $order_status = $order->post_status; $net_amount = $order_cost * $percentage / 100 + $extra_cost; $net_amount = apply_filters('dokan_order_net_amount', $net_amount, $order); $wpdb->insert($wpdb->prefix . 'dokan_orders', array('order_id' => $order_id, 'seller_id' => $seller_id, 'order_total' => $order_total, 'net_amount' => $net_amount, 'order_status' => $order_status), array('%d', '%d', '%f', '%f', '%s')); }
/** * Google Analytics eCommerce tracking * * @param int $order_id * * @return string */ protected function get_ecommerce_tracking_code($order_id) { // Get the order and output tracking code $order = new WC_Order($order_id); $logged_in = is_user_logged_in() ? 'yes' : 'no'; if ('yes' === $logged_in) { $user_id = get_current_user_id(); $current_user = get_user_by('id', $user_id); $username = $current_user->user_login; } else { $user_id = ''; $username = __('Guest', 'woocommerce-google-analytics-integration'); } if ('yes' == $this->ga_use_universal_analytics) { if (!empty($this->ga_set_domain_name)) { $set_domain_name = esc_js($this->ga_set_domain_name); } else { $set_domain_name = 'auto'; } $support_display_advertising = ''; if ('yes' == $this->ga_support_display_advertising) { $support_display_advertising = "ga('require', 'displayfeatures');"; } $anonymize_enabled = ''; if ('yes' == $this->ga_anonymize_enabled) { $anonymize_enabled = "ga('set', 'anonymizeIp', true);"; } $code = "\n\t(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){\n\t(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),\n\tm=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)\n\t})(window,document,'script','//www.google-analytics.com/analytics.js','ga');\n\n\tga('create', '" . esc_js($this->ga_id) . "', '" . $set_domain_name . "');" . $support_display_advertising . $anonymize_enabled . "\n\tga('set', 'dimension1', '" . $logged_in . "');\n\tga('send', 'pageview');\n\n\tga('require', 'ecommerce', 'ecommerce.js');\n\n\tga('ecommerce:addTransaction', {\n\t\t'id': '" . esc_js($order->get_order_number()) . "', // Transaction ID. Required\n\t\t'affiliation': '" . esc_js(get_bloginfo('name')) . "', // Affiliation or store name\n\t\t'revenue': '" . esc_js($order->get_total()) . "', // Grand Total\n\t\t'shipping': '" . esc_js($order->get_total_shipping()) . "', // Shipping\n\t\t'tax': '" . esc_js($order->get_total_tax()) . "', // Tax\n\t\t'currency': '" . esc_js($order->get_order_currency()) . "' // Currency\n\t});\n"; // Order items if ($order->get_items()) { foreach ($order->get_items() as $item) { $_product = $order->get_product_from_item($item); $code .= "ga('ecommerce:addItem', {"; $code .= "'id': '" . esc_js($order->get_order_number()) . "',"; $code .= "'name': '" . esc_js($item['name']) . "',"; $code .= "'sku': '" . esc_js($_product->get_sku() ? $_product->get_sku() : $_product->id) . "',"; if (isset($_product->variation_data)) { $code .= "'category': '" . esc_js(woocommerce_get_formatted_variation($_product->variation_data, true)) . "',"; } else { $out = array(); $categories = get_the_terms($_product->id, 'product_cat'); if ($categories) { foreach ($categories as $category) { $out[] = $category->name; } } $code .= "'category': '" . esc_js(join("/", $out)) . "',"; } $code .= "'price': '" . esc_js($order->get_item_total($item)) . "',"; $code .= "'quantity': '" . esc_js($item['qty']) . "'"; $code .= "});"; } } $code .= "ga('ecommerce:send'); // Send transaction and item data to Google Analytics."; } else { if ($this->ga_support_display_advertising == 'yes') { $ga_url = "('https:' == document.location.protocol ? 'https://' : 'http://') + 'stats.g.doubleclick.net/dc.js'"; } else { $ga_url = "('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'"; } $anonymize_enabled = ''; if ('yes' == $this->ga_anonymize_enabled) { $anonymize_enabled = "['_gat._anonymizeIp'],"; } if (!empty($this->ga_set_domain_name)) { $set_domain_name = "['_setDomainName', '" . esc_js($this->ga_set_domain_name) . "'],"; } else { $set_domain_name = ''; } $code = "\n\tvar _gaq = _gaq || [];\n\n\t_gaq.push(\n\t\t['_setAccount', '" . esc_js($this->ga_id) . "'], " . $set_domain_name . $anonymize_enabled . "\n\t\t['_setCustomVar', 1, 'logged-in', '" . esc_js($logged_in) . "', 1],\n\t\t['_trackPageview'],\n\t\t['_set', 'currencyCode', '" . esc_js($order->get_order_currency()) . "']\n\t);\n\n\t_gaq.push(['_addTrans',\n\t\t'" . esc_js($order->get_order_number()) . "', \t// order ID - required\n\t\t'" . esc_js(get_bloginfo('name')) . "', \t\t// affiliation or store name\n\t\t'" . esc_js($order->get_total()) . "', \t \t// total - required\n\t\t'" . esc_js($order->get_total_tax()) . "', \t// tax\n\t\t'" . esc_js($order->get_total_shipping()) . "',\t// shipping\n\t\t'" . esc_js($order->billing_city) . "', \t// city\n\t\t'" . esc_js($order->billing_state) . "', \t// state or province\n\t\t'" . esc_js($order->billing_country) . "' \t// country\n\t]);\n"; // Order items if ($order->get_items()) { foreach ($order->get_items() as $item) { $_product = $order->get_product_from_item($item); $code .= "_gaq.push(['_addItem',"; $code .= "'" . esc_js($order->get_order_number()) . "',"; $code .= "'" . esc_js($_product->get_sku() ? $_product->get_sku() : $_product->id) . "',"; $code .= "'" . esc_js($item['name']) . "',"; if (isset($_product->variation_data)) { $code .= "'" . esc_js(woocommerce_get_formatted_variation($_product->variation_data, true)) . "',"; } else { $out = array(); $categories = get_the_terms($_product->id, 'product_cat'); if ($categories) { foreach ($categories as $category) { $out[] = $category->name; } } $code .= "'" . esc_js(join("/", $out)) . "',"; } $code .= "'" . esc_js($order->get_item_total($item)) . "',"; $code .= "'" . esc_js($item['qty']) . "'"; $code .= "]);"; } } $code .= "\n\t_gaq.push(['_trackTrans']); // submits transaction to the Analytics servers\n\n\t(function() {\n\t\tvar ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n\t\tga.src = " . $ga_url . ";\n\t\tvar s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n\t})();\n"; } // Mark the order as tracked update_post_meta($order_id, '_ga_tracked', 1); return "\n<!-- WooCommerce Google Analytics Integration -->\n" . $this->get_generic_ga_code() . "\n<script type='text/javascript'>{$code}</script>\n<!-- /WooCommerce Google Analytics Integration -->\n"; }
/** * Process the payment and return the result * * @access public * @param int $order_id * @return array */ function process_payment($order_id) { global $woocommerce; $order = new WC_Order($order_id); $token = $_POST['payfortToken']; try { if (empty($token)) { $error_msg = __('Please make sure your card details have been entered correctly.', 'woocommerce'); throw new Start_Error($error_msg); } $charge_description = $order->id . ": WooCommerce charge for " . $order->billing_email; $order_items = $order->get_items(); $order_items_array_full = array(); $user_info = wp_get_current_user(); $user_name = $user_info->user_login; $udata = get_userdata($user_info->ID); if (isset($udata->user_registered)) { $registered_at = date(DATE_ISO8601, strtotime($udata->user_registered)); } else { $registered_at = date(DATE_ISO8601, strtotime(date("Y-m-d H:i:s"))); } foreach ($order_items as $key => $items) { $itemClass = new WC_Product($items['product_id']); $order_items_array['title'] = $items['name']; $order_items_array['amount'] = round($itemClass->get_price(), 2) * $this->currency_multiplier[get_woocommerce_currency()]; $order_items_array['quantity'] = $items['qty']; array_push($order_items_array_full, $order_items_array); } $billing_address = array("first_name" => $order->billing_first_name, "last_name" => $order->billing_last_name, "country" => $order->billing_country, "city" => $order->billing_city, "address_1" => $order->billing_address_1, "address_2" => $order->billing_address_2, "phone" => $order->billing_phone, "postcode" => $order->billing_postcode); $shipping_address = array("first_name" => $order->shipping_first_name, "last_name" => $order->shipping_last_name, "country" => $order->shipping_country, "city" => $order->shipping_city, "address_1" => $order->shipping_address_1, "address_2" => $order->shipping_address_2, "phone" => $order->shipping_phone, "postcode" => $order->shipping_postcode); $shopping_cart_array = array('user_name' => $user_name, 'registered_at' => $registered_at, 'items' => $order_items_array_full, 'billing_address' => $billing_address, 'shipping_address' => $shipping_address); $charge_args = array('description' => $charge_description, 'card' => $token, 'currency' => strtoupper(get_woocommerce_currency()), 'email' => $order->billing_email, 'ip' => $_SERVER['REMOTE_ADDR'], 'amount' => $order->get_total() * $this->currency_multiplier[get_woocommerce_currency()], 'shopping_cart' => $shopping_cart_array, 'shipping_amount' => round($order->get_total_shipping(), 2) * $this->currency_multiplier[get_woocommerce_currency()], 'metadata' => array('reference_id' => $order_id)); if ($this->test_mode == 'yes') { Start::setApiKey($this->test_secret_key); } else { Start::setApiKey($this->live_secret_key); } $start_plugin_data = get_file_data('wp-content/plugins/payfort/woocommerce-payfort.php', array('Version'), 'plugin'); $woo_plugin_data = get_file_data('wp-content/plugins/woocommerce/woocommerce.php', array('Version'), 'plugin'); $userAgent = 'WooCommerce ' . $woo_plugin_data['0'] . ' / Start Plugin ' . $start_plugin_data['0']; Start::setUserAgent($userAgent); $charge = Start_Charge::create($charge_args); // No exceptions? Yaay, all done! $order->payment_complete(); return array('result' => 'success', 'redirect' => $this->get_return_url($order)); } catch (Start_Error $e) { // TODO: Can we get the extra params (so the error is more apparent)? // e.g. Instead of "request params are invalid", we get // "extras":{"amount":["minimum amount (in the smallest currency unit) is 185 for AED"] $error_code = $e->getErrorCode(); if ($error_code === "card_declined") { $message = __('Error: ', 'woothemes') . $e->getMessage() . " Please, try with another card"; } else { $message = __('Error: ', 'woothemes') . $e->getMessage(); } // If function should we use? if (function_exists("wc_add_notice")) { // Use the new version of the add_error method wc_add_notice($message, 'error'); } else { // Use the old version $woocommerce->add_error($message); } // we raise 'update_checkout' event for javscript // to remove card token WC()->session->set('refresh_totals', true); return array('result' => 'fail', 'redirect' => ''); } }
/** * 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; }