/** * Get the total amount with or without refunds * @return string */ public function get_total() { $total = ''; if ($this->order->get_total_refunded() > 0) { $total_after_refund = $this->order->get_total() - $this->order->get_total_refunded(); $total = '<del class="total-without-refund">' . strip_tags($this->order->get_formatted_order_total()) . '</del> <ins>' . wc_price($total_after_refund, array('currency' => $this->order->get_order_currency())) . '</ins>'; } else { $total = $this->order->get_formatted_order_total(); } return $total; }
/** * Redirect to allPay */ public function receipt_page($order_id) { # Clean the cart global $woocommerce; $woocommerce->cart->empty_cart(); $order = new WC_Order($order_id); try { $this->invoke_allpay_module(); $aio = new AllInOne(); $aio->Send['MerchantTradeNo'] = ''; $service_url = ''; if ($this->allpay_test_mode == 'yes') { $service_url = 'http://payment-stage.allpay.com.tw/Cashier/AioCheckOut'; $aio->Send['MerchantTradeNo'] = date('YmdHis'); } else { $service_url = 'https://payment.allpay.com.tw/Cashier/AioCheckOut'; } $aio->MerchantID = $this->allpay_merchant_id; $aio->HashKey = $this->allpay_hash_key; $aio->HashIV = $this->allpay_hash_iv; $aio->ServiceURL = $service_url; $aio->Send['ReturnURL'] = add_query_arg('wc-api', 'WC_Gateway_Allpay', home_url('/')); $aio->Send['ClientBackURL'] = home_url('?page_id=' . get_option('woocommerce_myaccount_page_id') . '&view-order=' . $order->id); $aio->Send['MerchantTradeNo'] .= $order->id; $aio->Send['MerchantTradeDate'] = date('Y/m/d H:i:s'); # Set the product info $aio->Send['TotalAmount'] = $order->get_total(); array_push($aio->Send['Items'], array('Name' => '網路商品一批', 'Price' => $aio->Send['TotalAmount'], 'Currency' => $order->get_order_currency(), 'Quantity' => 1)); $aio->Send['TradeDesc'] = 'allPay_module_woocommerce_1_0_3'; # Get the chosen payment and installment $notes = $order->get_customer_order_notes(); $choose_payment = ''; $choose_installment = ''; if (isset($notes[0])) { list($choose_payment, $choose_installment) = explode('_', $notes[0]->comment_content); } $aio->Send['ChoosePayment'] = $choose_payment; # Set the extend information switch ($aio->Send['ChoosePayment']) { case 'Credit': # Do not support UnionPay $aio->SendExtend['UnionPay'] = false; # Credit installment parameters if (!empty($choose_installment)) { $aio->SendExtend['CreditInstallment'] = $choose_installment; $aio->SendExtend['InstallmentAmount'] = $aio->Send['TotalAmount']; $aio->SendExtend['Redeem'] = false; } break; case 'WebATM': break; case 'ATM': $aio->SendExtend['ExpireDate'] = 3; $aio->SendExtend['PaymentInfoURL'] = $aio->Send['ReturnURL']; break; case 'CVS': case 'BARCODE': $aio->SendExtend['Desc_1'] = ''; $aio->SendExtend['Desc_2'] = ''; $aio->SendExtend['Desc_3'] = ''; $aio->SendExtend['Desc_4'] = ''; $aio->SendExtend['PaymentInfoURL'] = $aio->Send['ReturnURL']; break; case 'Alipay': $aio->SendExtend['Email'] = $order->billing_email; $aio->SendExtend['PhoneNo'] = $order->billing_phone; $aio->SendExtend['UserName'] = $order->billing_first_name . ' ' . $order->billing_last_name; break; case 'Tenpay': $aio->SendExtend['ExpireTime'] = date('Y/m/d H:i:s', strtotime('+3 days')); break; case 'TopUpUsed': break; default: throw new Exception($this->tran('Invalid payment method.')); break; } $aio->CheckOut(); exit; } catch (Exception $e) { $this->add_error($e->getMessage()); } }
/** * Output the order tracking code for enabled networks * * @param int $order_id * * @return string */ public function output_order_tracking_code($order_id) { $order = new WC_Order($order_id); $code = "<script>fbq('track', 'Purchase', {value: '" . esc_js($order->get_total()) . "', currency: '" . esc_js($order->get_order_currency()) . "'});</script>"; $code .= '<noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=' . esc_js($this->facebook_id) . '&ev=Purchase&cd[value]=' . urlencode($order->get_total()) . '&cd[currency]=' . urlencode($order->get_order_currency()) . '&noscript=1" /></noscript>'; echo $code; }
/** * Check currency from IPN matches the order * @param WC_Order $order * @param string $currency */ protected function validate_currency($order, $currency) { // Validate currency if ($order->get_order_currency() != $currency) { WC_Gateway_Komoju::log('Payment error: Currencies do not match (sent "' . $order->get_order_currency() . '" | returned "' . $currency . '")'); // Put this order on-hold for manual checking $order->update_status('on-hold', sprintf(__('Validation error: Komoju currencies do not match (code %s).', 'woocommerce'), $currency)); exit; } }
public static function order_status_changed($id, $status = '', $new_status = '') { $rules = get_option('woorule_rules', array()); foreach ($rules as $k => $rule) { $enabled = get_option($rule['enabled']['id']) === 'yes' ? true : false; if ($enabled) { $which_event = get_option($rule['occurs']['id']); $is_opt_in_rule = false; $want_in = true; if (isset($rule['show_opt_in'])) { $is_opt_in_rule = get_option($rule['show_opt_in']['id']) === 'yes' ? true : false; } if ($is_opt_in_rule) { $want_in = get_post_meta($id, 'woorule_opt_in_' . $k, false); if (!empty($want_in)) { $want_in = $want_in[0] === 'yes' ? true : false; } } if ($want_in && $new_status === $which_event) { $integration = new WC_Integration_RuleMailer(); $order = new WC_Order($id); $user = $order->get_user(); $currency = $order->get_order_currency(); $order_subtotal = $order->order_total - ($order->order_shipping_tax + $order->order_shipping) - $order->cart_discount; $items = $order->get_items(); $brands = array(); $categories = array(); $tags = array(); foreach ($items as $item) { $p = new WC_Product_Simple($item['product_id']); $brands[] = $p->get_attribute('brand'); // this is bullshit $cat = strip_tags($p->get_categories('')); $tag = strip_tags($p->get_tags('')); if (!empty($cat)) { $categories[] = $cat; } if (!empty($tag)) { $tags[] = $tag; } } $subscription = array('apikey' => $integration->api_key, 'update_on_duplicate' => get_option($rule['update_on_duplicate']['id']) === 'yes' ? true : false, 'auto_create_tags' => get_option($rule['auto_create_tags']['id']) === 'yes' ? true : false, 'auto_create_fields' => get_option($rule['auto_create_fields']['id']) === 'yes' ? true : false, 'tags' => explode(',', get_option($rule['tags']['id'])), 'subscribers' => array('email' => $order->billing_email, 'phone_number' => $order->billing_phone, 'fields' => array(array('key' => 'Order.Number', 'value' => $order->get_order_number()), array('key' => 'Order.Date', 'value' => $order->order_date), array('key' => 'Order.FirstName', 'value' => $order->billing_first_name), array('key' => 'Order.LastName', 'value' => $order->billing_last_name), array('key' => 'Order.Street1', 'value' => $order->billing_address_1), array('key' => 'Order.Street2', 'value' => $order->billing_address_2), array('key' => 'Order.City', 'value' => $order->billing_city), array('key' => 'Order.Country', 'value' => $order->billing_country), array('key' => 'Order.State', 'value' => $order->billing_state), array('key' => 'Order.Subtotal', 'value' => $order_subtotal), array('key' => 'Order.Discount', 'value' => $order->cart_discount), array('key' => 'Order.Shipping', 'value' => $order->order_shipping + $order->order_shipping_tax), array('key' => 'Order.Total', 'value' => $order->order_total), array('key' => 'Order.Vat', 'value' => $order->order_tax)))); if (!empty($categories)) { $subscription['subscribers']['fields'][] = array('key' => 'Order.Categories', 'value' => $categories, 'type' => 'multiple'); } if (!empty($tags)) { $subscription['subscribers']['fields'][] = array('key' => 'Order.Tags', 'value' => array($tags), 'type' => 'multiple'); } if (!empty($brands)) { $subscription['subscribers']['fields'][] = array('key' => 'Order.Brands', 'value' => $brands, 'type' => 'multiple'); } $api = WP_RuleMailer_API::get_instance(); $api::subscribe($integration->api_url, $subscription); } } } }
/** * Get refund request args * @param WC_Order $order * @param float $amount * @param string $reason * @return array */ public static function get_request($order, $amount = null, $reason = '') { $request = array('VERSION' => '84.0', 'SIGNATURE' => self::$api_signature, 'USER' => self::$api_username, 'PWD' => self::$api_password, 'METHOD' => 'RefundTransaction', 'TRANSACTIONID' => $order->get_transaction_id(), 'NOTE' => html_entity_decode(wc_trim_string($reason, 255), ENT_NOQUOTES, 'UTF-8'), 'REFUNDTYPE' => 'Full'); if (!is_null($amount)) { $request['AMT'] = number_format($amount, 2, '.', ''); $request['CURRENCYCODE'] = $order->get_order_currency(); $request['REFUNDTYPE'] = 'Partial'; } return apply_filters('woocommerce_paypal_refund_request', $request, $order, $amount, $reason); }
/** * Setup the DoCapture request * * @link https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoCapture_API_Operation_NVP/ * @link https://developer.paypal.com/webapps/developer/docs/classic/admin/auth-capture/ * * @since 3.0.0 * @param WC_Order $order order object */ public function do_capture(WC_Order $order) { $this->set_method('DoCapture'); $this->add_parameters(array('AUTHORIZATIONID' => $order->paypal_express_transaction_id, 'AMT' => $order->capture_total, 'CURRENCYCODE' => $order->get_order_currency(), 'COMPLETETYPE' => 'Complete', '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))), 'NOTE' => $order->description)); }
public function epay_meta_box_payment() { global $post, $woocommerce; $order = new WC_Order($post->ID); $transactionId = get_post_meta($order->id, 'Transaction ID', true); require_once epay_LIB . 'class.epaysoap.php'; if (strlen($transactionId) > 0) { try { $webservice = new epaysoap($this->remotepassword); $transaction = $webservice->gettransaction($this->merchant, $transactionId); if (!is_wp_error($transaction)) { echo '<p>'; echo '<strong>' . _e('Transaction ID', 'woocommerce-gateway-epay-dk') . ':</strong> ' . $transaction->transactionInformation->transactionid; echo '</p>'; echo '<p>'; echo '<strong>' . _e('Authorized amount', 'woocommerce-gateway-epay-dk') . ':</strong> ' . $order->get_order_currency() . ' ' . number_format($transaction->transactionInformation->authamount / 100, 2, ".", ""); echo '</p>'; echo '<p>'; echo '<strong>' . _e('Captured amount', 'woocommerce-gateway-epay-dk') . ':</strong> ' . $order->get_order_currency() . ' ' . number_format($transaction->transactionInformation->capturedamount / 100, 2, ".", ""); echo '</p>'; echo '<p>'; echo '<strong>' . _e('Credited amount', 'woocommerce-gateway-epay-dk') . ':</strong> ' . $order->get_order_currency() . ' ' . number_format($transaction->transactionInformation->creditedamount / 100, 2, ".", ""); echo '</p>'; if ($transaction->transactionInformation->status == "PAYMENT_NEW") { echo '<ul>'; echo '<li>'; echo '<p>'; echo $order->get_order_currency() . ' <span><input type="text" value="' . number_format(($transaction->transactionInformation->authamount - $transaction->transactionInformation->capturedamount) / 100, 2, ".", "") . '" id="epay_amount" name="epay_amount" /></span>'; echo '</p>'; echo '<a class="button" onclick="javascript:location.href=\'' . admin_url('post.php?post=' . $post->ID . '&action=edit&epay_action=capture') . '&amount=\' + document.getElementById(\'epay_amount\').value">'; echo _e('Capture', 'woocommerce-gateway-epay-dk'); echo '</a>'; echo '</li>'; echo '</ul><br />'; echo '<a class="button" href="' . admin_url('post.php?post=' . $post->ID . '&action=edit&epay_action=delete') . '">'; echo _e('Delete', 'woocommerce-gateway-epay-dk'); echo '</a>'; } elseif ($transaction->transactionInformation->status == "PAYMENT_CAPTURED" && $transaction->transactionInformation->creditedamount == 0) { echo '<ul>'; echo '<li>'; echo '<p>'; echo $order->get_order_currency() . ' <span><input type="text" value="' . number_format($transaction->transactionInformation->capturedamount / 100, 2, ".", "") . '" id="epay_credit_amount" name="epay_credit_amount" /></span>'; echo '</p>'; echo '<a class="button" onclick="javascript: (confirm(\'' . __('Are you sure you want to credit?', 'woocommerce-gateway-epay-dk') . '\') ? (location.href=\'' . admin_url('post.php?post=' . $post->ID . '&action=edit&epay_action=credit') . '&amount=\' + document.getElementById(\'epay_credit_amount\').value) : (false));">'; echo _e('Credit', 'woocommerce-gateway-epay-dk'); echo '</a>'; echo '</li>'; echo '</ul><br />'; } echo '<br /><br />'; $historyArray = $transaction->transactionInformation->history->TransactionHistoryInfo; if (!array_key_exists(0, $transaction->transactionInformation->history->TransactionHistoryInfo)) { $historyArray = array($transaction->transactionInformation->history->TransactionHistoryInfo); } for ($i = 0; $i < count($historyArray); $i++) { echo str_replace("T", " ", $historyArray[$i]->created) . ": "; if (strlen($historyArray[$i]->username) > 0) { echo $historyArray[$i]->username . ": "; } echo $historyArray[$i]->eventMsg . "<br />"; } } else { foreach ($transaction->get_error_messages() as $error) { throw new Exception($error->get_error_message()); } } } catch (Exception $e) { echo $this->message("error", $e->getMessage()); } } else { echo "No transaction was found."; } }
/** * Capture and log when customer completes checkout * * @param int $order_id * @return void */ public function capture_sale_events($order_ids, $historic = false) { $products = array(); foreach ($order_ids as $order_id) { $exported = get_post_meta($order_id, '_wc_graphflow_exported', true); if ('yes' !== $exported) { $order = new WC_Order($order_id); if (!$order) { return; } $order_currency = $order->get_order_currency(); $order_id = $order->id; $customer_ip_address = $order->customer_ip_address; $customer_user_agent = $order->customer_user_agent; // extract order status, different for WC 2.1 vs 2.2 if (defined('WOOCOMMERCE_VERSION') && version_compare(WOOCOMMERCE_VERSION, '2.2', '>=')) { $order_status = $order->get_status(); } else { $order_status = $order->status; } foreach ($order->get_items() as $order_item_id => $order_item) { // extract the user id for the order if ($historic == true) { $order_user = isset($order->customer_user) ? $order->customer_user : $order->billing_email; if ($order_user == 0) { $order_user = $order->billing_email; } } else { $order_user = $this->get_user_id(); } // check if we can get the product, log an error message if not. $product = get_product($order_item['product_id']); if (!$product) { $this->get_api()->log->add("graphflow", "Failed to get_product for id: " . $order_item['product_id'] . " during order export for order id: " . $order->id); continue; } $this->maybe_capture_product($order_item['product_id']); // timestamp in UTC $time = new DateTime($order->order_date); $time->setTimezone(new DateTimeZone('UTC')); $timestamp_utc = $time->getTimestamp() * 1000; $graphflow_order_item = array('fromId' => $order_user, 'toId' => $order_item['product_id'], 'interactionType' => 'purchase', 'price' => $product->get_price(), 'quantity' => $order_item['qty'], 'interactionData' => array('order_currency' => $order_currency, 'transactionId' => $order_id, 'remoteAddr' => $customer_ip_address, 'uaRaw' => $customer_user_agent, 'order_status' => $order_status), 'timestamp' => $timestamp_utc); $products[] = $graphflow_order_item; } // For historical orders, only capture if not already captured if ($historic == false || 'yes' != get_user_meta($order_user, '_wc_graphflow_exported', true)) { $this->capture_customer($order_user, $historic); } } } if (!empty($products)) { $this->get_api()->add_user_interactions($products); } foreach ($order_ids as $order_id) { // Set a meta field so we do not export again when visiting thanks page for this order update_post_meta($order_id, '_wc_graphflow_exported', 'yes'); } }
/** * Process refund * * If the gateway declares 'refunds' support, this will allow it to refund * a passed in amount. * * @param int $order_id * @param float $amount * @param string $reason * @return boolean True or false based on success, or a WP_Error object */ public function process_refund($order_id, $amount = null, $reason = '') { global $woocommerce; $order = new WC_Order($order_id); $this->params["amount"] = (int) ($amount * 100); $this->params["reference"] = $order_id . "-" . time(); // It is not possible to simply refund against the order ID as multiple reunds are permitted... $this->params["transaction_id"] = get_post_meta($order_id, '_transaction_id', true); if (empty($this->params['transaction_id'])) { $this->params["transaction_id"] = $this->fetch_fatzebra_transaction_id($order_id); } $this->params["customer_ip"] = $this->get_customer_real_ip(); $this->params["currency"] = $order->get_order_currency(); $test_mode = $this->settings['test_mode'] == 'yes'; $this->params["test"] = $test_mode; $sandbox_mode = $this->settings["sandbox_mode"] == "yes"; // Yup, the checkbox settings return as 'yes' or 'no' $order_text = json_encode($this->params); $url = $sandbox_mode ? $this->sandbox_url : ($url = $this->live_url); // URL is for /refunds $url = str_replace('purchases', 'refunds', $url); $args = array('method' => 'POST', 'body' => $order_text, 'headers' => array('Authorization' => 'Basic ' . base64_encode($this->settings["username"] . ":" . $this->settings["token"]), 'X-Test-Mode' => $test_mode, 'User-Agent' => "WooCommerce Plugin " . $this->version), 'timeout' => 30); try { $this->response = (array) wp_remote_request($url, $args); if ((int) $this->response["response"]["code"] != 200 && (int) $this->response["response"]["code"] != 201) { wc_add_notice("Refund failed: " . $this->response["response"]["message"], 'error'); return false; } $this->response_data = json_decode($this->response['body']); if (!$this->response_data->successful) { wc_add_notice('Refund Failed - Gateway Error: ' . implode(",", $this->response_data->errors), 'error'); return false; } if (!$this->response_data->response->successful) { wc_add_notice('Refund Declined: ' . $this->response_data->response->message, 'error'); return false; } if ($this->response_data->response->successful) { wc_add_notice('Refund Approved'); $order->add_order_note('Refund for ' . $amount . ' successful. Refund ID: ' . $this->response_data->response->id); return true; } } catch (Exception $e) { wc_add_notice("Unknown Refund Error - please see error log", "error"); error_log("Exception caught during refund: " . print_r($e, true)); return false; } return false; }
/** * Output the order tracking code for facebook * * @param WC_Order $order * * @return string */ public function output_facebook_order_code($order) { if (!$this->facebook_id) { return; } $code = '<script>/* <![CDATA[ */ (function() { var _fbq = window._fbq || (window._fbq = []); if (!_fbq.loaded) { var fbds = document.createElement(\'script\'); fbds.async = true; fbds.src = \'//connect.facebook.net/en_US/fbds.js\'; var s = document.getElementsByTagName(\'script\')[0]; s.parentNode.insertBefore(fbds, s); _fbq.loaded = true; } })(); window._fbq = window._fbq || []; window._fbq.push([\'track\', \'' . esc_js($this->facebook_id) . '\', {\'value\':\'' . esc_js($order->get_total()) . '\',\'currency\':\'' . esc_js($order->get_order_currency()) . '\'}]); /* ]]> */</script>'; $code .= '<noscript><img height="1" width="1" alt="" style="display:none" src="https://www.facebook.com/tr?ev=' . urlencode($this->facebook_id) . '&cd[value]=' . urlencode($order->get_total()) . '&cd[currency]=' . urlencode($order->get_order_currency()) . '&noscript=1" /></noscript>'; echo $code; }
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; } }
/** * Hosted payment args. * * @param WC_Order $order * * @return array */ protected function get_hosted_payments_args($order) { $args = apply_filters('woocommerce_stripe_hosted_args', array('key' => $this->public_key, 'amount' => $this->get_amount($order->order_total, $order->get_order_currency()), 'currency' => strtolower($order->get_order_currency() ? $order->get_order_currency() : get_woocommerce_currency()), 'name' => esc_html(get_bloginfo('name')), 'description' => sprintf(__('Order #%s', 'yith-stripe'), $order->get_order_number()), 'zip-code' => $order->billing_postcode, 'label' => __('Proceed to payment', 'yith-stripe'), 'email' => $order->billing_email, 'image' => $this->modal_image, 'capture' => 'true'), $order->id); return $args; }
function process_payment($order_id) { global $woocommerce; $order = new WC_Order($order_id); $order_number = $order->get_order_number(); $receiveCurrency = strtoupper(trim($this->get_option('receive_currency'))); $currency = $order->get_order_currency(); $amount = $order->get_total(); if ($currency != $receiveCurrency) { $receiveAmount = $this->unitConversion($amount, $currency, $receiveCurrency); } else { $receiveAmount = $amount; } if (!$receiveAmount || $receiveAmount < 0) { echo 'Spectrocoin is not fully configured. Please select different payment'; exit; } $scMerchantClient = new SCMerchantClient(SC_API_URL, $this->get_option('merchant_id'), $this->get_option('project_id'), $this->get_option('private_key')); set_query_var('invoice_id', $order_number); $callbackUrl = add_query_arg(array('wc-api' => 'WC_Gateway_Spectrocoin', 'invoice_id' => $order_number), home_url('/')); $createOrderRequest = new CreateOrderRequest(null, 0, $receiveAmount, '', 'en', $callbackUrl, $order->get_checkout_order_received_url(), $woocommerce->cart->get_checkout_url()); $createOrderResponse = $scMerchantClient->createOrder($createOrderRequest); if ($createOrderResponse instanceof ApiError) { $this->log('Error occurred: '); $this->log($createOrderResponse->getCode()); $this->log($createOrderResponse->getMessage()); } else { if ($createOrderResponse instanceof CreateOrderResponse) { return array('result' => 'success', 'redirect' => $createOrderResponse->getRedirectUrl()); } } return; }
/** * Capture payment when the order is changed from on-hold to complete or processing * * @param int $order_id */ public function capture_payment($order_id) { $order = new WC_Order($order_id); $txn_id = get_post_meta($order_id, '_transaction_id', true); $captured = get_post_meta($order_id, '_paypalpro_charge_captured', true); if ($order->payment_method === 'paypal_pro' && $txn_id && $captured === 'no') { $paypalpro = new WC_Gateway_PayPal_Pro(); $url = $paypalpro->testmode ? $paypalpro->testurl : $paypalpro->liveurl; $post_data = array('VERSION' => $paypalpro->api_version, 'SIGNATURE' => $paypalpro->api_signature, 'USER' => $paypalpro->api_username, 'PWD' => $paypalpro->api_password, 'METHOD' => 'DoCapture', 'AUTHORIZATIONID' => $txn_id, 'AMT' => $order->get_total(), 'CURRENCYCODE' => $order->get_order_currency(), 'COMPLETETYPE' => 'Complete'); if ($paypalpro->soft_descriptor) { $post_data['SOFTDESCRIPTOR'] = $paypalpro->soft_descriptor; } $response = wp_remote_post($url, array('method' => 'POST', 'headers' => array('PAYPAL-NVP' => 'Y'), 'body' => $post_data, 'timeout' => 70, 'user-agent' => 'WooCommerce', 'httpversion' => '1.1')); if (is_wp_error($response)) { $order->add_order_note(__('Unable to capture charge!', 'woocommerce-gateway-paypal-pro') . ' ' . $response->get_error_message()); } else { parse_str($response['body'], $parsed_response); $order->add_order_note(sprintf(__('PayPal Pro charge complete (Transaction ID: %s)', 'woocommerce-gateway-paypal-pro'), $parsed_response['TRANSACTIONID'])); update_post_meta($order->id, '_paypalpro_charge_captured', 'yes'); // update the transaction ID of the capture update_post_meta($order->id, '_transaction_id', $parsed_response['TRANSACTIONID']); } } if ($order->payment_method === 'paypal_pro_payflow' && $txn_id && $captured === 'no') { $paypalpro_payflow = new WC_Gateway_PayPal_Pro_PayFlow(); $url = $paypalpro_payflow->testmode ? $paypalpro_payflow->testurl : $paypalpro_payflow->liveurl; $post_data = array(); $post_data['USER'] = $paypalpro_payflow->paypal_user; $post_data['VENDOR'] = $paypalpro_payflow->paypal_vendor; $post_data['PARTNER'] = $paypalpro_payflow->paypal_partner; $post_data['PWD'] = $paypalpro_payflow->paypal_password; $post_data['TRXTYPE'] = 'D'; // payflow only allows delayed capture for authorized only transactions $post_data['ORIGID'] = $txn_id; if ($paypalpro_payflow->soft_descriptor) { $post_data['MERCHDESCR'] = $paypalpro_payflow->soft_descriptor; } $response = wp_remote_post($url, array('method' => 'POST', 'body' => urldecode(http_build_query($post_data, null, '&')), 'timeout' => 70, 'user-agent' => 'WooCommerce', 'httpversion' => '1.1')); parse_str($response['body'], $parsed_response); if (is_wp_error($response)) { $order->add_order_note(__('Unable to capture charge!', 'woocommerce-gateway-paypal-pro') . ' ' . $response->get_error_message()); } elseif ($parsed_response['RESULT'] !== '0') { $order->add_order_note(__('Unable to capture charge!', 'woocommerce-gateway-paypal-pro')); // log it $paypalpro_payflow->log('Parsed Response ' . print_r($parsed_response, true)); } else { $order->add_order_note(sprintf(__('PayPal Pro (Payflow) delay charge complete (PNREF: %s)', 'woocommerce-gateway-paypal-pro'), $parsed_response['PNREF'])); update_post_meta($order->id, '_paypalpro_charge_captured', 'yes'); // update the transaction ID of the capture update_post_meta($order->id, '_transaction_id', $parsed_response['PNREF']); } } return true; }
/** * 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 **/ function process_payment($order_id) { global $woocommerce; $this->params["customer_ip"] = $this->get_customer_real_ip(); $defer_payment = $this->parent_settings["deferred_payments"] == "yes"; $test_mode = $this->parent_settings["test_mode"] == "yes"; $order = new WC_Order($order_id); $this->params["currency"] = $order->get_order_currency(); if (class_exists("WC_Subscriptions_Order") && WC_Subscriptions_Order::order_contains_subscription($order)) { // No deferred payments for subscriptions. $defer_payment = false; // Charge sign up fee + first period here.. // Periodic charging should happen via scheduled_subscription_payment_fatzebra $this->params["amount"] = (int) (WC_Subscriptions_Order::get_total_initial_payment($order) * 100); } else { $this->params["amount"] = (int) ($order->order_total * 100); } $this->params["reference"] = (string) $order_id; $this->params["test"] = $test_mode; $this->params["deferred"] = $defer_payment; $this->params["wallet"] = array("type" => "VISA", "callid" => $_POST['callid']); if (isset($_POST['token'])) { $this->params['card_token'] = $_POST['token']; } if ($this->parent_settings['fraud_data'] == 'yes') { $fz_base = new WC_FatZebra(); $fraud_data = $fz_base->get_fraud_payload($order); $this->params['fraud'] = $fraud_data; } if ($this->params["amount"] === 0) { $result = $this->tokenize_card($this->params); } else { $result = $this->do_payment($this->params); } if (is_wp_error($result)) { switch ($result->get_error_code()) { case 1: // Non-200 response, so failed... (e.g. 401, 403, 500 etc). $order->add_order_note($result->get_error_message()); wc_add_notice($result->get_error_message(), 'error'); break; case 2: // Gateway error (data etc) $errors = $result->get_error_data(); foreach ($errors as $error) { $order->add_order_note("Gateway Error: " . $error); } error_log("WooCommerce Fat Zebra - Gateway Error: " . print_r($errors, true)); wc_add_notice("Payment Failed: " . implode(", ", $errors), 'error'); break; case 3: // Declined - error data is array with keys: message, id $order->add_order_note(__("Payment Declined: " . $this->response_data->response->message . ". Reference: " . $this->response_data->response->transaction_id)); wc_add_notice("Payment declined: " . $this->response_data->response->message, 'error'); if (isset($this->response_data->response->fraud_result) && !empty($this->response_data->response->fraud_result)) { if ($this->response_data->response->fraud_result == 'Accept') { $order->add_order_note("Fraud Check Result: Accept"); } else { $order->add_order_note("Fraud Check Result: " . $this->response_data->response->fraud_result . " - " . implode(", ", $this->response_data->response->fraud_messages)); } } break; case 4: // Exception caught, something bad happened. Data is exception // Exception caught, something bad happened. Data is exception default: wc_add_notice("Unknown error.", 'error'); $order->add_order_note(__("Unknown Error (exception): " . print_r($result->get_error_data(), true))); break; } return; } else { // Success! Returned is an array with the transaction ID etc // For a deferred payment we set the status to on-hold and then add a detailed note for review. if ($defer_payment) { $date = new DateTime($result["card_expiry"], new DateTimeZone("Australia/Sydney")); $note = "Deferred Payment:<ul><li>Card Token: " . $result["card_token"] . "</li><li>Card Holder: " . $result["card_holder"] . "</li><li>Card Number: " . $result["card_number"] . "</li><li>Expiry: " . $date->format("m/Y") . "</li></ul>"; $order->update_status("on-hold", $note); update_post_meta($order_id, "_fatzebra_card_token", $result["card_token"]); update_post_meta($order_id, "fatzebra_card_token", $result["card_token"]); } else { if ($this->params["amount"] === 0) { $order->add_order_note(__("Fat Zebra payment complete - \$0 initial amount, card tokenized. Card token: " . $result["card_token"])); } else { $order->add_order_note(__("Fat Zebra payment complete. Reference: " . $result["transaction_id"])); } if (isset($this->response_data->response->fraud_result) && !empty($this->response_data->response->fraud_result)) { if ($this->response_data->response->fraud_result == 'Accept') { $order->add_order_note("Fraud Check Result: Accept"); } else { $order->add_order_note("Fraud Check Result: " . $this->response_data->response->fraud_result . " - " . implode(", ", $this->response_data->response->fraud_messages)); } } $order->payment_complete($result['transaction_id']); // Clear the session values $this->clear_visa_checkout_session_values(); // Store the card token as post meta update_post_meta($order_id, "_fatzebra_card_token", $result["card_token"]); update_post_meta($order_id, "fatzebra_card_token", $result["card_token"]); } $woocommerce->cart->empty_cart(); return array('result' => 'success', 'redirect' => $this->get_return_url($order)); } }
/** * Sets WooCommerce Order in request * * @param WC_Order $order * * @return $this */ public function set_order(WC_Order $order) { $customer = array(); if ($this->check_string_length($order->billing_first_name, 2, 50)) { $customer['givenName'] = $order->billing_first_name; } if ($this->check_string_length($order->billing_last_name, 2, 50)) { $customer['surname'] = $order->billing_last_name; } if ($this->check_string_length($order->billing_company, 1, 40)) { $customer['companyName'] = $order->billing_company; } if ($this->check_string_length($order->billing_phone, 6, 25)) { $customer['phone'] = $order->billing_phone; } if ($this->check_string_length($order->billing_email, 6, 128)) { $customer['email'] = $order->billing_email; } if ($this->check_string_length($order->customer_ip_address, 1, 255)) { $customer['ip'] = $order->customer_ip_address; } $billing = array(); if ($this->check_string_length($order->billing_address_1, 2, 50)) { $billing['street1'] = $order->billing_address_1; } if ($this->check_string_length($order->billing_address_2, 2, 50)) { $billing['street2'] = $order->billing_address_2; } if ($this->check_string_length($order->billing_city, 2, 30)) { $billing['city'] = $order->billing_city; } if ($this->check_string_length($order->billing_state, 2, 50)) { $billing['state'] = $order->billing_state; } if ($this->check_string_length($order->billing_postcode, 1, 10)) { $billing['postcode'] = $order->billing_postcode; } if ($this->check_string_length($order->billing_country, 2, 2)) { $billing['country'] = $order->billing_country; } $shipping = array(); if ($this->check_string_length($order->shipping_first_name, 2, 50)) { $shipping['givenName'] = $order->shipping_first_name; } if ($this->check_string_length($order->shipping_last_name, 2, 50)) { $shipping['surname'] = $order->shipping_last_name; } if ($this->check_string_length($order->shipping_address_1, 2, 50)) { $shipping['street1'] = $order->shipping_address_1; } if ($this->check_string_length($order->shipping_address_2, 2, 50)) { $shipping['street2'] = $order->shipping_address_2; } if ($this->check_string_length($order->shipping_city, 2, 30)) { $shipping['city'] = $order->shipping_city; } if ($this->check_string_length($order->shipping_state, 2, 50)) { $shipping['state'] = $order->shipping_state; } if ($this->check_string_length($order->shipping_postcode, 1, 10)) { $shipping['postcode'] = $order->shipping_postcode; } if ($this->check_string_length($order->shipping_country, 2, 2)) { $shipping['country'] = $order->shipping_country; } $orderItems = $order->get_items(); $i = 0; foreach ($orderItems as $orderItem) { if ($orderItem['type'] == 'line_item') { $this->data['cart.items[' . $i . '].name'] = urlencode($orderItem['name']); $this->data['cart.items[' . $i . '].quantity'] = $orderItem['qty']; $i++; } } $this->set_amount(sprintf('%0.2f', $order->get_total()))->set_currency($order->get_order_currency())->set_merchant_transaction_id($this->generate_trans_id($order->id))->add_custom_param('orderId', $order->id)->set_customer($customer)->set_billing($billing)->set_shipping($shipping); $this->order = $order; return $this; }
function orderpost($orderId) { global $wpdb; $testMode = get_option('linksync_test'); $LAIDKey = get_option('linksync_laid'); $apicall = new linksync_class($LAIDKey, $testMode); //Checking for already sent Order $sentOrderIds = get_option('linksync_sent_order_id'); if (isset($sentOrderIds)) { if (!empty($sentOrderIds)) { $order_id_array = unserialize($sentOrderIds); } else { $order_id_array = array(); } if (!in_array($orderId, $order_id_array)) { $order = new WC_Order($orderId); if ($order->post_status == get_option('order_status_wc_to_vend')) { update_option('linksync_sent_order_id', serialize(array_merge($order_id_array, array($orderId)))); $order_no = $order->get_order_number(); if (strpos($order_no, '#') !== false) { $order_no = str_replace('#', '', $order_no); } $get_total = $order->get_total(); $get_user = $order->get_user(); $comments = $order->post->post_excerpt; $primary_email_address = $get_user->data->user_email; $currency = $order->get_order_currency(); $shipping_method = $order->get_shipping_method(); $order_total = $order->get_order_item_totals(); $transaction_id = $order->get_transaction_id(); $taxes_included = false; $total_discount = $order->get_total_discount(); $total_quantity = 0; $registerDb = get_option('wc_to_vend_register'); $vend_uid = get_option('wc_to_vend_user'); $total_tax = $order->get_total_tax(); // Geting Payment object details if (isset($order_total['payment_method']['value']) && !empty($order_total['payment_method']['value'])) { $wc_payment = get_option('wc_to_vend_payment'); if (isset($wc_payment) && !empty($wc_payment)) { $total_payments = explode(",", $wc_payment); foreach ($total_payments as $mapped_payment) { $exploded_mapped_payment = explode("|", $mapped_payment); if (isset($exploded_mapped_payment[1]) && !empty($exploded_mapped_payment[1]) && isset($exploded_mapped_payment[0]) && !empty($exploded_mapped_payment[0])) { if ($exploded_mapped_payment[1] == $order_total['payment_method']['value']) { $vend_payment_data = explode("%%", $exploded_mapped_payment[0]); if (isset($vend_payment_data[0])) { $payment_method = $vend_payment_data[0]; } if (isset($vend_payment_data[1])) { $payment_method_id = $vend_payment_data[1]; } break; } } } } $payment = array("retailer_payment_type_id" => isset($payment_method_id) ? $payment_method_id : null, "amount" => isset($get_total) ? $get_total : 0, "method" => isset($payment_method) ? $payment_method : null, "transactionNumber" => isset($transaction_id) ? $transaction_id : null); } $export_user_details = get_option('wc_to_vend_export'); if (isset($export_user_details) && !empty($export_user_details)) { if ($export_user_details == 'customer') { //woocommerce filter $billingAddress_filter = apply_filters('woocommerce_order_formatted_billing_address', array('firstName' => $order->billing_first_name, 'lastName' => $order->billing_last_name, 'phone' => $order->billing_phone, 'street1' => $order->billing_address_1, 'street2' => $order->billing_address_2, 'city' => $order->billing_city, 'state' => $order->billing_state, 'postalCode' => $order->billing_postcode, 'country' => $order->billing_country, 'company' => $order->billing_company, 'email_address' => $order->billing_email), $order); $billingAddress = array('firstName' => $billingAddress_filter['firstName'], 'lastName' => $billingAddress_filter['lastName'], 'phone' => $billingAddress_filter['phone'], 'street1' => $billingAddress_filter['street1'], 'street2' => $billingAddress_filter['street2'], 'city' => $billingAddress_filter['city'], 'state' => $billingAddress_filter['state'], 'postalCode' => $billingAddress_filter['postalCode'], 'country' => $billingAddress_filter['country'], 'company' => $billingAddress_filter['company'], 'email_address' => $billingAddress_filter['email_address']); $deliveryAddress_filter = apply_filters('woocommerce_order_formatted_shipping_address', array('firstName' => $order->shipping_first_name, 'lastName' => $order->shipping_last_name, 'phone' => $order->shipping_phone, 'street1' => $order->shipping_address_1, 'street2' => $order->shipping_address_2, 'city' => $order->shipping_city, 'state' => $order->shipping_state, 'postalCode' => $order->shipping_postcode, 'country' => $order->shipping_country, 'company' => $order->shipping_company), $order); $deliveryAddress = array('firstName' => $deliveryAddress_filter['firstName'], 'lastName' => $deliveryAddress_filter['lastName'], 'phone' => $deliveryAddress_filter['phone'], 'street1' => $deliveryAddress_filter['street1'], 'street2' => $deliveryAddress_filter['street2'], 'city' => $deliveryAddress_filter['city'], 'state' => $deliveryAddress_filter['state'], 'postalCode' => $deliveryAddress_filter['postalCode'], 'country' => $deliveryAddress_filter['country'], 'company' => $deliveryAddress_filter['company']); $primary_email = isset($primary_email_address) ? $primary_email_address : $billingAddress['email_address']; unset($billingAddress['email_address']); } } $vend_user_detail = get_option('wc_to_vend_user'); if (isset($vend_user_detail) && !empty($vend_user_detail)) { $user = explode('|', $vend_user_detail); $vend_uid = isset($user[0]) ? $user[0] : null; $vend_username = isset($user[1]) ? $user[1] : null; } //Ordered product(s) $items = $order->get_items(); $taxes = $order->get_taxes(); foreach ($items as $item) { foreach ($taxes as $tax_label) { $sql = mysql_query("SELECT tax_rate_id FROM `" . $wpdb->prefix . "woocommerce_tax_rates` WHERE tax_rate_name='" . $tax_label['label'] . "' AND tax_rate_class='" . $item['item_meta']['_tax_class'][0] . "'"); if (mysql_num_rows($sql) != 0) { $tax_classes = linksync_tax_classes($tax_label['label'], $item['item_meta']['_tax_class'][0]); if ($tax_classes['result'] == 'success') { $vend_taxes = explode('/', $tax_classes['tax_classes']); } } } $taxId = isset($vend_taxes[0]) ? $vend_taxes[0] : null; $taxName = isset($vend_taxes[1]) ? $vend_taxes[1] : null; $taxRate = isset($vend_taxes[2]) ? $vend_taxes[2] : null; if (isset($item['variation_id']) && !empty($item['variation_id'])) { $product_id = $item['variation_id']; } else { $product_id = $item['product_id']; } $pro_object = new WC_Product($product_id); $itemtotal = (double) $item['item_meta']['_line_subtotal'][0]; if (isset($item['line_subtotal']) && !empty($item['line_subtotal'])) { $product_amount = (double) ($item['line_subtotal'] / $item['qty']); } $discount = (double) $item['item_meta']['_line_subtotal'][0] - (double) $item['item_meta']['_line_total'][0]; if (isset($discount) && !empty($discount)) { $discount = (double) ($discount / $item['qty']); } #---------Changes--------# //Product Amount = product org amount - discount amount $product_total_amount = (double) $product_amount - (double) $discount; $product_sku = $pro_object->get_sku(); if (isset($product_total_amount) && isset($taxRate) && !empty($product_total_amount) && !empty($taxRate)) { $taxValue = $product_total_amount * $taxRate; } $products[] = array('sku' => $product_sku, 'title' => $item['name'], 'price' => $product_total_amount, 'quantity' => $item['qty'], 'discountAmount' => isset($discount) ? $discount : 0, 'taxName' => isset($taxName) ? $taxName : null, 'taxId' => isset($taxId) ? $taxId : null, 'taxRate' => isset($taxRate) ? $taxRate : null, 'taxValue' => isset($taxValue) ? $taxValue : null, 'discountTitle' => isset($discountTitle) ? $discountTitle : 'sale'); $total_quantity += $item['qty']; unset($taxId); unset($taxName); unset($taxRate); unset($taxValue); } #---------Discount-----# // if (isset($total_discount) && !empty($total_discount)) { // $taxes_Discount = $apicall->linksync_getTaxes(); // if (isset($taxes_Discount) && !empty($taxes_Discount)) { // if (!isset($taxes_Discount['errorCode'])) { // if (isset($taxes_Discount['taxes'])) { // foreach ($taxes_Discount['taxes'] as $select_tax) { // if ($select_tax['name'] == 'GST') { // $discountTaxName = $select_tax['name']; // $discountTaxId = $select_tax['id']; // $discountTaxRate = $select_tax['rate']; // } // } // } // } // } // if (isset($total_discount)) { // if (isset($discountTaxRate) && !empty($discountTaxRate)) { // $taxValue_discount = $discountTaxRate * $total_discount; // } // } // $products[] = array( // "price" => isset($total_discount) ? $total_discount : null, // "quantity" => 1, // "sku" => "vend-discount", // 'taxName' => isset($discountTaxName) ? $discountTaxName : null, // 'taxId' => isset($discountTaxId) ? $discountTaxId : null, // 'taxRate' => isset($discountTaxRate) ? $discountTaxRate : null, // 'taxValue' => isset($taxValue_discount) ? $taxValue_discount : null // ); // $products[] = array( // "price" => isset($total_discount) ? $total_discount : null, // "quantity" => 1, // "sku" => "vend-discount", // 'taxName' => null, // 'taxId' => null, // 'taxRate' => null, // 'taxValue' => null // ); // } #----------Shipping------------# foreach ($taxes as $tax_label) { if (isset($tax_label['shipping_tax_amount']) && !empty($tax_label['shipping_tax_amount'])) { $tax_classes = linksync_tax_classes($tax_label['label'], $item['item_meta']['_tax_class'][0]); if ($tax_classes['result'] == 'success') { $vend_taxes = explode('/', $tax_classes['tax_classes']); $taxId_shipping = isset($vend_taxes[0]) ? $vend_taxes[0] : null; $taxName_shipping = isset($vend_taxes[1]) ? $vend_taxes[1] : null; $taxRate_shipping = isset($vend_taxes[2]) ? $vend_taxes[2] : null; } } } if (isset($shipping_method) && !empty($shipping_method)) { $shipping_cost = $order->get_total_shipping(); $shipping_with_tax = $order->get_shipping_tax(); if ($shipping_with_tax > 0) { if (isset($shipping_cost) && isset($taxRate_shipping) && !empty($shipping_cost) && !empty($taxRate_shipping)) { $taxValue_shipping = $shipping_cost * $taxRate_shipping; } } $products[] = array("price" => isset($shipping_cost) ? $shipping_cost : null, "quantity" => 1, "sku" => "shipping", 'taxName' => isset($taxName_shipping) ? $taxName_shipping : null, 'taxId' => isset($taxId_shipping) ? $taxId_shipping : null, 'taxRate' => isset($taxRate_shipping) ? $taxRate_shipping : null, 'taxValue' => isset($taxValue_shipping) ? $taxValue_shipping : null); } //UTC Time date_default_timezone_set("UTC"); $order_created = date("Y-m-d H:i:s", time()); $OrderArray = array('uid' => isset($vend_uid) ? $vend_uid : null, 'created' => isset($order_created) ? $order_created : null, "orderId" => isset($order_no) ? $order_no : null, "source" => "WooCommerce", 'register_id' => isset($registerDb) ? $registerDb : null, 'user_name' => isset($vend_username) ? $vend_username : null, 'primary_email' => isset($primary_email) && !empty($primary_email) ? $primary_email : null, 'total' => isset($get_total) ? $get_total : 0, 'total_tax' => isset($total_tax) ? $total_tax : 0, 'comments' => isset($comments) ? $comments : null, 'taxes_included' => $taxes_included, 'currency' => isset($currency) ? $currency : 'USD', 'shipping_method' => isset($shipping_method) ? $shipping_method : null, 'payment' => isset($payment) && !empty($payment) ? $payment : null, 'products' => isset($products) && !empty($products) ? $products : null, 'payment_type_id' => isset($payment_method_id) ? $payment_method_id : null, 'billingAddress' => isset($billingAddress) && !empty($billingAddress) ? $billingAddress : null, 'deliveryAddress' => isset($deliveryAddress) && !empty($deliveryAddress) ? $deliveryAddress : null); $json = json_encode($OrderArray); $apicall->linksync_postOrder($json); linksync_class::add('Order Sync Woo to Vend', 'success', 'Woo Order no:' . $order_no, $LAIDKey); } } else { linksync_class::add('Order Sync Woo to Vend', 'Error', 'Already Sent Order', $LAIDKey); } } }
/** * Mark an order as voided. Because WC has no status for "void", we use * refunded. * * @since 3.1.0 * @param WC_Order $order order object */ protected function mark_order_as_voided($order, $response) { $message = sprintf(_x('%s Void in the amount of %s approved.', 'Supports void charge', $this->text_domain), $this->get_method_title(), wc_price($order->refund->amount, array('currency' => $order->get_order_currency()))); // adds the transaction id (if any) to the order note if ($response->get_transaction_id()) { $message .= ' ' . sprintf(_x('(Transaction ID %s)', 'Supports void charge', $this->text_domain), $response->get_transaction_id()); } // Mark order as refunded if not already set if (!SV_WC_Plugin_Compatibility::order_has_status($order, 'refunded')) { $order->update_status('refunded', $message); } else { $order->add_order_note($message); } }
function get_monthly_sales_report() { $execution_time_start = microtime(true); $months_array = array(''); $months_days_array = array(__('Days', 'woocommerce-jetpack')); $total_orders_array = array(__('Total Orders', 'woocommerce-jetpack')); $total_orders_average_array = array(__('Orders Average / Day', 'woocommerce-jetpack')); $total_orders_sum_array = array(__('Total Sum', 'woocommerce-jetpack')); $total_orders_sum_excl_tax_array = array(__('Total Sum (excl. TAX)', 'woocommerce-jetpack')); $total_orders_sum_average_order_array = array(__('Average / Order (excl. TAX)', 'woocommerce-jetpack')); $total_orders_sum_average_array = array(__('Average / Day (excl. TAX)', 'woocommerce-jetpack')); $currency_rates_array = array(__('Currency Rates', 'woocommerce-jetpack')); $total_months_days = 0; $total_orders_total = 0; $total_orders_sum_total = 0; $total_orders_sum_excl_tax_total = 0; $order_currencies_array = array(); $report_currency = isset($_GET['currency']) && 'merge' != $_GET['currency'] ? $_GET['currency'] : get_woocommerce_currency(); $block_size = 96; $table_data = array(); for ($i = 1; $i <= 12; $i++) { $current_months_averages = array(); $total_orders = 0; $total_orders_sum = 0; $total_orders_sum_excl_tax = 0; $offset = 0; $day_for_average = $i == date('m') && $this->year == date('Y') ? date('d') - 1 : date('t', strtotime($this->year . '-' . sprintf('%02d', $i) . '-' . '01')); if (0 == $day_for_average) { $months_array[] = date_i18n('F', mktime(0, 0, 0, $i, 1, $this->year)); $months_days_array[] = '-'; $total_orders_array[] = '-'; $total_orders_average_array[] = '-'; $total_orders_sum_array[] = '-'; $total_orders_sum_excl_tax_array[] = '-'; $total_orders_sum_average_order_array[] = '-'; $total_orders_sum_average_array[] = '-'; $currency_rates_array[] = ''; continue; } while (true) { $args_orders = array('post_type' => 'shop_order', 'post_status' => 'wc-completed', 'posts_per_page' => $block_size, 'orderby' => 'date', 'order' => 'DESC', 'offset' => $offset, 'date_query' => array('after' => array('year' => $this->year, 'month' => $i, 'day' => 1), 'before' => array('year' => $this->year, 'month' => $i, 'day' => $day_for_average), 'inclusive' => true)); $loop_orders = new WP_Query($args_orders); if (!$loop_orders->have_posts()) { break; } while ($loop_orders->have_posts()) { $loop_orders->the_post(); $order_id = $loop_orders->post->ID; $order = new WC_Order($order_id); $order_currency = $order->get_order_currency(); if (!isset($order_currencies_array[$order_currency])) { $order_currencies_array[$order_currency] = 0; } $order_currencies_array[$order_currency]++; $total_orders++; $order_total = $order->get_total(); $order_total_excl_tax = $order->get_total() - $order->get_total_tax(); if (!isset($current_months_averages[$order_currency][$report_currency])) { $start_date = $this->year . '-' . sprintf('%02d', $i) . '-' . '01'; $end_date = date('Y-m-t', strtotime($start_date)); $the_rate = $this->get_exchange_rate_average($order_currency, $report_currency, $start_date, $end_date); if (false === $the_rate) { // Try previous month $start_date_prev_month = date('Y-m-d', strtotime('first day of last month', strtotime($start_date))); $end_date_prev_month = date('Y-m-t', strtotime($start_date_prev_month)); $the_rate = $this->get_exchange_rate_average($order_currency, $report_currency, $start_date_prev_month, $end_date_prev_month); if (false === $the_rate) { return '<p>' . sprintf(__('Error getting currency rate for %s', 'woocommerce-jetpack'), $order_currency . $report_currency) . '</p>'; } } $current_months_averages[$order_currency][$report_currency] = $the_rate; } $total_orders_sum += $order_total * $current_months_averages[$order_currency][$report_currency]; $total_orders_sum_excl_tax += $order_total_excl_tax * $current_months_averages[$order_currency][$report_currency]; } $offset += $block_size; } // Month Name $months_array[] = date_i18n('F', mktime(0, 0, 0, $i, 1, $this->year)); // Month Days $months_days_array[] = date('m') >= $i || $this->year != date('Y') ? $day_for_average : '-'; $total_months_days += date('m') >= $i || $this->year != date('Y') ? $day_for_average : 0; // Sales $total_orders_array[] = $total_orders > 0 ? $total_orders : '-'; $total_orders_total += $total_orders; // Sales Average $average_sales_result = $total_orders / $day_for_average; $total_orders_average_array[] = $average_sales_result > 0 ? number_format($average_sales_result, 2, '.', ',') : '-'; // Sum $total_orders_sum_array[] = $total_orders_sum > 0 ? $report_currency . ' ' . number_format($total_orders_sum, 2, '.', ',') : '-'; $total_orders_sum_total += $total_orders_sum; // Sum excl. Tax //if ( $total_orders_sum != $total_orders_sum_excl_tax) { $total_orders_sum_excl_tax_array[] = $total_orders_sum_excl_tax > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax, 2, '.', ',') : '-'; $total_orders_sum_excl_tax_total += $total_orders_sum_excl_tax; //} // Order Average $total_orders_sum_average_order_array[] = $total_orders_sum_excl_tax > 0 && $total_orders > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax / $total_orders, 2, '.', ',') : '-'; // Sum Average $average_result = $total_orders_sum_excl_tax / $day_for_average; $total_orders_sum_average_array[] = $average_result > 0 ? $report_currency . ' ' . number_format($average_result, 2, '.', ',') : '-'; // Currency Rates // if ( isset( $_GET['show_rates'] ) ) { ksort($current_months_averages, true); // $currency_rates_html = '<pre style="font-size:8px;">' . print_r( $current_months_averages, true ) . '</pre>'; $currency_rates_html = '<pre style="font-size:x-small;">'; foreach ($current_months_averages as $currency_from => $currencies_to) { foreach ($currencies_to as $currency_to => $rate) { if ($currency_from != $currency_to) { $currency_rates_html .= $currency_from . $currency_to . '~' . number_format($rate, 4) . '<br>'; } } } $currency_rates_html .= '</pre>'; // } $currency_rates_array[] = $currency_rates_html; } // Totals $months_array[] = __('Totals', 'woocommerce-jetpack'); $months_days_array[] = $total_months_days; $total_orders_array[] = $total_orders_total; $total_orders_average_array[] = $total_months_days > 0 ? number_format($total_orders_total / $total_months_days, 2, '.', ',') : '-'; $total_orders_sum_array[] = $report_currency . ' ' . number_format($total_orders_sum_total, 2, '.', ','); $total_orders_sum_excl_tax_array[] = $report_currency . ' ' . number_format($total_orders_sum_excl_tax_total, 2, '.', ','); $total_orders_sum_average_order_array[] = $total_orders_total > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax_total / $total_orders_total, 2, '.', ',') : '-'; $total_orders_sum_average_array[] = $total_months_days > 0 ? $report_currency . ' ' . number_format($total_orders_sum_excl_tax_total / $total_months_days, 2, '.', ',') : '-'; $currency_rates_array[] = ''; // Table $table_data[] = $months_array; $table_data[] = $months_days_array; $table_data[] = $total_orders_array; $table_data[] = $total_orders_average_array; $table_data[] = $total_orders_sum_array; $table_data[] = $total_orders_sum_excl_tax_array; $table_data[] = $total_orders_sum_average_order_array; $table_data[] = $total_orders_sum_average_array; $table_data[] = $currency_rates_array; /* foreach ( $order_currencies_array as $order_currency => $total_currency_orders ) { $table_data[] = array( $order_currency . ' (' . $total_currency_orders . ')' ); } */ $execution_time_end = microtime(true); // HTML $html = ''; $menu = ''; $menu .= '<ul class="subsubsub">'; $menu .= '<li><a href="' . add_query_arg('year', date('Y')) . '" class="' . ($this->year == date('Y') ? 'current' : '') . '">' . date('Y') . '</a> | </li>'; $menu .= '<li><a href="' . add_query_arg('year', date('Y') - 1) . '" class="' . ($this->year == date('Y') - 1 ? 'current' : '') . '">' . (date('Y') - 1) . '</a> | </li>'; $menu .= '</ul>'; $menu .= '<br class="clear">'; $html .= $menu; $html .= '<h4>' . __('Report currency', 'woocommerce-jetpack') . ': ' . $report_currency . '</h4>'; $months_styles = array(); for ($i = 1; $i <= 12; $i++) { $months_styles[] = 'width:6%;'; } $html .= wcj_get_table_html($table_data, array('table_class' => 'widefat striped', 'table_heading_type' => 'horizontal', 'columns_styles' => array_merge(array('width:16%;'), $months_styles, array('width:12%;font-weight:bold;')))); $html .= '<p style="font-size:x-small;"><em>' . sprintf(__('Report generated in: %s s', 'woocommerce-jetpack'), number_format($execution_time_end - $execution_time_start, 2, '.', ',')) . '</em></p>'; $html .= '<form method="post" action="">' . '<input name="wcj_reset_currency_rates" type="submit" class="button button-primary" value="' . __('Reset Currency Rates', 'woocommerce-jetpack') . '">' . '</form>'; // $html .= '<pre>' . print_r( get_option( 'wcj_reports_currency_rates' ), true ) . '</pre>'; return $html; }
/** * Generate the request for the payment. * @param WC_Order $order * @param object $source * @return array() */ protected function generate_payment_request($order, $source) { $post_data = array(); $post_data['currency'] = strtolower($order->get_order_currency() ? $order->get_order_currency() : get_woocommerce_currency()); $post_data['amount'] = $this->get_stripe_amount($order->get_total(), $post_data['currency']); $post_data['description'] = sprintf(__('%s - Order %s', 'woocommerce-gateway-stripe'), wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES), $order->get_order_number()); $post_data['capture'] = $this->capture ? 'true' : 'false'; if (!empty($order->billing_email) && apply_filters('wc_stripe_send_stripe_receipt', false)) { $post_data['receipt_email'] = $order->billing_email; } $post_data['expand[]'] = 'balance_transaction'; if ($source->customer) { $post_data['customer'] = $source->customer; } if ($source->source) { $post_data['source'] = $source->source; } return $post_data; }
/** * PayU IPN Request * * @access public * @param $_POST * @return void */ function payu_ipn_request() { $posted = stripslashes_deep($_POST); if (empty($posted)) { $this->log->add('payu', sprintf(__('PayU IPN Request Failure. %s', 'wc-payu') . $posted)); wp_die(__('PayU IPN Request Failure.', 'wc-payu')); } $order_ref = explode("-", $posted['REFNOEXT']); $order_id = $order_ref[0]; $order = new WC_Order($order_id); if ($order) { // PayU függvények betöltése require_once 'includes/payu.class.php'; $config = $this->get_payu_config($order->get_order_currency()); $ipn = new PayUIpn($config); if ($this->debug == 'yes') { $ipn->logger = true; $ipn->log_path = WC_LOG_DIR; } if ($ipn->validateReceived()) { /* [REFNO] => 11186529 [REFNOEXT] => 63 [ORDERSTATUS] => COMPLETE [PAYMETHOD] => Visa/MasterCard/Eurocard [PAYMETHOD_CODE] => CCVISAMC */ if ($order->status == $this->waiting_payment_status) { $order->update_status($this->succesfull_payment_status, __('Succesfull payment.', 'wc-payu')); $order->reduce_order_stock(); $order->add_order_note(sprintf(__('IPN STATUS: %s', 'wc-payu'), $_POST['ORDERSTATUS'])); echo $ipn->confirmReceived(); } else { echo __('Not waiting status. Not sending email, or not update orders status.', 'wc-payu'); } exit; } } else { echo __('Can not query data in the orders. Not sending email, or not update orders status.', 'wc-payu'); exit; } }
/** * 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 wooPaymentCharged($orderId) { $visitorId = $this->getVisitorId(); if (!$visitorId) { return false; } $order = new WC_Order($orderId); $curreny = $order->get_order_currency(); $amount = $order->get_total(); $response = $this->tidioOne->request('api/track', array('name' => 'payment charged', 'visitorId' => $visitorId)); }
/** * Mark an order as voided. Because WC has no status for "void", we use * refunded. * * @since 3.1.0 * @param WC_Order $order order object */ public function mark_order_as_voided($order, $response) { $message = sprintf(esc_html__('%1$s Void in the amount of %2$s approved.', 'woocommerce-plugin-framework'), $this->get_method_title(), wc_price($order->refund->amount, array('currency' => $order->get_order_currency()))); // adds the transaction id (if any) to the order note if ($response->get_transaction_id()) { $message .= ' ' . sprintf(esc_html__('(Transaction ID %s)', 'woocommerce-plugin-framework'), $response->get_transaction_id()); } // mark order as cancelled, since no money was actually transferred if (!$order->has_status('cancelled')) { $this->voided_order_message = $message; add_filter('woocommerce_order_fully_refunded_status', array($this, 'maybe_cancel_voided_order'), 10, 2); } else { $order->add_order_note($message); } }
/** * Process the payment */ public function process_payment($order_id) { $order = new WC_Order($order_id); $this->log('Processing order #' . $order_id); $card_number = isset($_POST['paypal_pro-card-number']) ? wc_clean($_POST['paypal_pro-card-number']) : ''; $card_cvc = isset($_POST['paypal_pro-card-cvc']) ? wc_clean($_POST['paypal_pro-card-cvc']) : ''; $card_expiry = isset($_POST['paypal_pro-card-expiry']) ? wc_clean($_POST['paypal_pro-card-expiry']) : ''; // Format values $card_number = str_replace(array(' ', '-'), '', $card_number); $card_expiry = array_map('trim', explode('/', $card_expiry)); $card_exp_month = str_pad($card_expiry[0], 2, "0", STR_PAD_LEFT); $card_exp_year = $card_expiry[1]; if (isset($_POST['paypal_pro-card-start'])) { $card_start = wc_clean($_POST['paypal_pro-card-start']); $card_start = array_map('trim', explode('/', $card_start)); $card_start_month = str_pad($card_start[0], 2, "0", STR_PAD_LEFT); $card_start_year = $card_start[1]; } else { $card_start_month = ''; $card_start_year = ''; } if (strlen($card_exp_year) == 2) { $card_exp_year += 2000; } /** * 3D Secure Handling */ if ($this->enable_3dsecure) { if (!class_exists('CentinelClient')) { include_once 'lib/CentinelClient.php'; } $this->clear_centinel_session(); $centinelClient = new CentinelClient(); $centinelClient->add("MsgType", "cmpi_lookup"); $centinelClient->add("Version", "1.7"); $centinelClient->add("ProcessorId", $this->centinel_pid); $centinelClient->add("MerchantId", $this->centinel_mid); $centinelClient->add("TransactionPwd", $this->centinel_pwd); $centinelClient->add("UserAgent", $_SERVER["HTTP_USER_AGENT"]); $centinelClient->add("BrowserHeader", $_SERVER["HTTP_ACCEPT"]); $centinelClient->add("TransactionType", 'C'); // Standard cmpi_lookup fields $centinelClient->add('OrderNumber', $order_id); $centinelClient->add('Amount', $order->order_total * 100); $centinelClient->add('CurrencyCode', $this->iso4217[$order->get_order_currency()]); $centinelClient->add('TransactionMode', 'S'); // Items $item_loop = 0; if (sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $item) { $item_loop++; $centinelClient->add('Item_Name_' . $item_loop, $item['name']); $centinelClient->add('Item_Price_' . $item_loop, number_format($order->get_item_total($item, true, true) * 100)); $centinelClient->add('Item_Quantity_' . $item_loop, $item['qty']); $centinelClient->add('Item_Desc_' . $item_loop, $item['name']); } } // Payer Authentication specific fields $centinelClient->add('CardNumber', $card_number); $centinelClient->add('CardExpMonth', $card_exp_month); $centinelClient->add('CardExpYear', $card_exp_year); // Send request $centinelClient->sendHttp($this->centinel_url, "5000", "15000"); $this->log('Centinal client request: ' . print_r($centinelClient->request, true)); $this->log('Centinal client response: ' . print_r($centinelClient->response, true)); // Save response in session WC()->session->set("paypal_pro_orderid", $order_id); // Save lookup response in session WC()->session->set("Centinel_cmpiMessageResp", $centinelClient->response); WC()->session->set("Centinel_Enrolled", $centinelClient->getValue("Enrolled")); WC()->session->set("Centinel_TransactionId", $centinelClient->getValue("TransactionId")); WC()->session->set("Centinel_ACSUrl", $centinelClient->getValue("ACSUrl")); WC()->session->set("Centinel_Payload", $centinelClient->getValue("Payload")); WC()->session->set("Centinel_ErrorNo", $centinelClient->getValue("ErrorNo")); WC()->session->set("Centinel_ErrorDesc", $centinelClient->getValue("ErrorDesc")); WC()->session->set("Centinel_EciFlag", $centinelClient->getValue("EciFlag")); WC()->session->set("Centinel_TransactionType", "C"); WC()->session->set('Centinel_TermUrl', WC()->api_request_url('WC_Gateway_PayPal_Pro', true)); WC()->session->set('Centinel_OrderId', $centinelClient->getValue("OrderId")); $this->log('3dsecure Centinel_Enrolled: ' . WC()->session->get('Centinel_Enrolled')); /******************************************************************************/ /* */ /* Result Processing Logic */ /* */ /******************************************************************************/ if (WC()->session->get('Centinel_ErrorNo') == 0) { if (WC()->session->get('Centinel_Enrolled') == 'Y') { $this->log('Doing 3dsecure payment authorization'); $this->log('ASCUrl: ' . WC()->session->get("Centinel_ACSUrl")); $this->log('PaReq: ' . WC()->session->get("Centinel_Payload")); $this->log('TermUrl: ' . WC()->session->get("Centinel_TermUrl")); @ob_clean(); ?> <html> <head> <title>3DSecure Payment Authorisation</title> </head> <body> <form name="frmLaunchACS" id="3ds_submit_form" method="POST" action="<?php echo WC()->session->get("Centinel_ACSUrl"); ?> "> <input type="hidden" name="PaReq" value="<?php echo WC()->session->get("Centinel_Payload"); ?> "> <input type="hidden" name="TermUrl" value="<?php echo WC()->session->get('Centinel_TermUrl'); ?> "> <input type="hidden" name="MD" value="<?php echo urlencode(json_encode(array('card' => $card_number, 'csc' => $card_cvc, 'card_exp_month' => $card_exp_month, 'card_exp_year' => $card_exp_year, 'card_start_month' => $card_start_month, 'card_start_year' => $card_start_year, 'order_id' => $order_id))); ?> "> <noscript> <div class="woocommerce_message"><?php _e('Processing your Payer Authentication Transaction', 'woocommerce-gateway-paypal-pro'); ?> - <?php _e('Please click Submit to continue the processing of your transaction.', 'woocommerce-gateway-paypal-pro'); ?> <input type="submit" class="button" id="3ds_submit" value="Submit" /></div> </noscript> </form> <script> document.frmLaunchACS.submit(); </script> </body> </html> <?php exit; } elseif ($this->liability_shift && WC()->session->get('Centinel_Enrolled') != 'N') { wc_add_notice(__('Authentication unavailable. Please try a different payment method or card.', 'woocommerce-gateway-paypal-pro'), 'error'); return; } else { // Customer not-enrolled, so just carry on with PayPal process return $this->do_payment($order, $card_number, '', $card_exp_month, $card_exp_year, $card_cvc, $card_start_month, $card_start_year, '', WC()->session->get('Centinel_Enrolled'), '', WC()->session->get("Centinel_EciFlag"), ''); } } else { wc_add_notice(__('Error in 3D secure authentication: ', 'woocommerce-gateway-paypal-pro') . WC()->session->get('Centinel_ErrorNo'), 'error'); return; } } // Do payment with paypal return $this->do_payment($order, $card_number, '', $card_exp_month, $card_exp_year, $card_cvc, $card_start_month, $card_start_year); }
/** * Format prices * * @param float|int $price * @param WC_Order $order * * @return float|int */ protected function number_format($price, $order) { $decimals = 2; if (!$this->currency_has_decimals($order->get_order_currency())) { $decimals = 0; } return number_format($price, $decimals, '.', ''); }
/** * @param array $qs * * @return array */ public static function get_history($qs) { $orders = array(); foreach ($qs as $item => $values) { $order = new WC_Order($qs[$item]->ID); $orderDate = new DateTime($order->order_date); $orders[] = array('id' => (string) $order->id, 'amount' => Aplazame_Filters::decimals($order->get_total()), 'due' => '', 'status' => $order->get_status(), 'type' => Aplazame_Helpers::get_payment_method($order->id), 'order_date' => $orderDate->format(DATE_ISO8601), 'currency' => $order->get_order_currency(), 'billing' => self::get_address($order, 'billing'), 'shipping' => self::get_shipping_info($order)); } return $orders; }
/** * Gets Order product Price in voucher code * * @package WooCommerce - PDF Vouchers * @since 1.1.0 */ public function woo_vou_get_formatted_product_price($orderid, $item, $tax_display = '') { //Get prefix $prefix = WOO_VOU_META_PREFIX; //Get Order $woo_order = new WC_Order($orderid); if (!$tax_display) { $tax_display = $woo_order->tax_display_cart; } if (!isset($item['line_subtotal']) || !isset($item['line_subtotal_tax'])) { return ''; } //get multipdf option in ordermeta $multiple_pdf = get_post_meta($orderid, $prefix . 'multiple_pdf', true); //Get Item quantity $item_qty = isset($item['qty']) ? $item['qty'] : ''; if ('excl' == $tax_display) { $ex_tax_label = $woo_order->prices_include_tax ? 1 : 0; $line_subtotal = $woo_order->get_line_subtotal($item); if ($multiple_pdf == 'yes' && !empty($item_qty)) { $line_subtotal = $line_subtotal / $item_qty; } $subtotal = wc_price($line_subtotal, array('ex_tax_label' => $ex_tax_label, 'currency' => $woo_order->get_order_currency())); } else { $line_subtotal = $woo_order->get_line_subtotal($item, true); if ($multiple_pdf == 'yes' && !empty($item_qty)) { $line_subtotal = $line_subtotal / $item_qty; } $subtotal = wc_price($line_subtotal, array('currency' => $woo_order->get_order_currency())); } return apply_filters('woo_vou_get_formatted_product_price', $subtotal, $orderid, $item, $tax_display); }