function meta_box() { global $woocommerce, $post; $order = new WC_Order($post->ID); $order_discount = $order->get_total_discount(); $order_tax = $order->get_total_tax(); $order_subtotal = $order->get_subtotal_to_display(); $order_total = $order->get_formatted_order_total(); get_payment_gateway_fields('paypal'); woocommerce_wp_select(array('id' => 'payment_type', 'label' => '', 'value' => 'default', 'options' => ins_get_payment_methods(), 'class' => 'chosen-select')); woocommerce_wp_select(array('id' => 'add_coupon', 'label' => '', 'value' => 'default', 'options' => ins_get_coupons(), 'class' => 'chosen-select')); woocommerce_wp_text_input(array('id' => 'sub_total', 'label' => __('Order Subtotal', 'instore'), 'placeholder' => 0.0, 'value' => $order_subtotal)); woocommerce_wp_text_input(array('id' => 'order_tax', 'label' => __('Order Tax', 'instore'), 'placeholder' => 0.0, 'value' => $order_tax)); woocommerce_wp_text_input(array('id' => 'applied_discount', 'label' => __('Applied Discount', 'instore'), 'placeholder' => 0.0, 'value' => $order_discount)); }
/** * 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; }
/** * @param WC_Order $order * * @return array */ public static function get_order($order) { $serializer = array('id' => (string) $order->id, 'articles' => self::get_articles($order->get_items()), 'currency' => get_woocommerce_currency(), 'total_amount' => Aplazame_Filters::decimals($order->get_total()), 'discount' => Aplazame_Filters::decimals($order->get_total_discount())); return $serializer; }
/** * Process the payment and return the result * * @access public * @param int $order_id * @return array */ public function process_payment($order_id) { $this->init_mijireh(); $mj_order = new Mijireh_Order(); $wc_order = new WC_Order($order_id); // add items to order $items = $wc_order->get_items(); foreach ($items as $item) { $product = $wc_order->get_product_from_item($item); if (get_option('woocommerce_prices_include_tax') == 'yes') { $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, true, false), $item['qty'], $product->get_sku()); } else { $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item, false, true), $item['qty'], $product->get_sku()); } } // Handle fees $items = $wc_order->get_fees(); foreach ($items as $item) { $mj_order->add_item($item['name'], number_format($item['line_total'], 2, '.', ','), 1, ''); } // add billing address to order $billing = new Mijireh_Address(); $billing->first_name = $wc_order->billing_first_name; $billing->last_name = $wc_order->billing_last_name; $billing->street = $wc_order->billing_address_1; $billing->apt_suite = $wc_order->billing_address_2; $billing->city = $wc_order->billing_city; $billing->state_province = $wc_order->billing_state; $billing->zip_code = $wc_order->billing_postcode; $billing->country = $wc_order->billing_country; $billing->company = $wc_order->billing_company; $billing->phone = $wc_order->billing_phone; if ($billing->validate()) { $mj_order->set_billing_address($billing); } // add shipping address to order $shipping = new Mijireh_Address(); $shipping->first_name = $wc_order->shipping_first_name; $shipping->last_name = $wc_order->shipping_last_name; $shipping->street = $wc_order->shipping_address_1; $shipping->apt_suite = $wc_order->shipping_address_2; $shipping->city = $wc_order->shipping_city; $shipping->state_province = $wc_order->shipping_state; $shipping->zip_code = $wc_order->shipping_postcode; $shipping->country = $wc_order->shipping_country; $shipping->company = $wc_order->shipping_company; if ($shipping->validate()) { $mj_order->set_shipping_address($shipping); } // set order name $mj_order->first_name = $wc_order->billing_first_name; $mj_order->last_name = $wc_order->billing_last_name; $mj_order->email = $wc_order->billing_email; // set order totals $mj_order->total = $wc_order->get_total(); $mj_order->discount = $wc_order->get_total_discount(); if (get_option('woocommerce_prices_include_tax') == 'yes') { $mj_order->shipping = round($wc_order->get_total_shipping() + $wc_order->get_shipping_tax(), 2); $mj_order->show_tax = false; } else { $mj_order->shipping = round($wc_order->get_total_shipping(), 2); $mj_order->tax = $wc_order->get_total_tax(); } // add meta data to identify woocommerce order $mj_order->add_meta_data('wc_order_id', $order_id); // Set URL for mijireh payment notificatoin - use WC API $mj_order->return_url = str_replace('https:', 'http:', add_query_arg('wc-api', 'WC_Gateway_Mijireh', home_url('/'))); // Identify woocommerce $mj_order->partner_id = 'woo'; try { $mj_order->create(); $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url); return $result; } catch (Mijireh_Exception $e) { wc_add_notice(__('Mijireh error:', 'woocommerce') . $e->getMessage(), 'error'); } }
function 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); }
function sendCustomerInvoice($order_id) { PlexLog::addLog(' Info =>@sendCustomerInvoice order_id=' . $order_id); $wooCommerceOrderObject = new WC_Order($order_id); $user_id = $wooCommerceOrderObject->get_user_id(); $customerMailId = $wooCommerceOrderObject->billing_email; $invoice_mail_content = ''; $invoice_mail_content .= ' <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_container"> <tbody> <tr> <td align="center" valign="top"> <font face="Arial" style="font-weight:bold;background-color:#8fd1c8;color:#202020;"></font> <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_header" bgcolor="#8fd1c8"> <tbody> <tr > <td width="20" height="20" bgcolor="#8fd1c8"> </td> <td bgcolor="#8fd1c8"> </td> <td width="20" bgcolor="#8fd1c8"> </td> </tr> <tr > <td width="20" bgcolor="#8fd1c8"> </td> <td bgcolor="#8fd1c8" style="font-weight:bold;font-size:24px;color:#ffffff;" ><h2 style="margin:0;">Welcome to ' . get_option('blogname') . '! <br>Thank you for your order. We\'ll be in touch shortly with additional order and shipping information.</h2></td> <td width="20" bgcolor="#8fd1c8"> </td> </tr> <tr > <td width="20" height="20" bgcolor="#8fd1c8"> </td> <td bgcolor="#8fd1c8"> </td> <td width="20" bgcolor="#8fd1c8"> </td> </tr> </tbody> </table> </td> </tr> <tr> <td align="center" valign="top"> <table border="0" cellpadding="0" cellspacing="0" width="600" id="template_body"> <tbody> <tr> <td valign="top"> <font style="background-color:#f9f9f9"> <table border="0" cellpadding="20" cellspacing="0" width="100%"> <tbody> <tr> <td valign="top"> <div> <font face="Arial" align="left" style="font-size:18px;color:#8a8a8a"> <p>Your order #' . get_post_meta($order_id, "plexOrderId", true) . ' has been received and is now being processed. Your order details are shown below for your reference:</p> <table cellspacing="0" cellpadding="6" border="1" style="width:100%;"> <thead> <tr> <th scope="col"> <font align="left">Product</font> </th> <th scope="col"> <font align="left">Quantity</font> </th> <th scope="col"> <font align="left">Price</font> </th> </tr> </thead> <tbody>'; $allItems = $wooCommerceOrderObject->get_items(); foreach ($allItems as $key => $value) { $invoice_mail_content .= ' <tr> <td> <font align="left">' . $value["name"] . '<br><small></small></font> </td> <td> <font align="left">' . $value["qty"] . '</font> </td> <td> <font align="left"> <span class="amount">$' . $value["line_subtotal"] . '</span> </font> </td> </tr>'; } $invoice_mail_content .= ' </tbody> <tfoot style="text-align: left;"> <tr> <th scope="row" colspan="2"> <font align="left">Cart Subtotal:</font> </th> <td> <font align="left"> <span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_subtotal()) . '</span> </font> </td> </tr>'; if ($wooCommerceOrderObject->get_total_discount() > 0.0) { $invoice_mail_content .= '<tr> <th scope="row" colspan="2"> <font align="left">Discount:</font> </th> <td> <font align="left"> <span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_total_discount()) . '</span> </font> </td> </tr>'; } $invoice_mail_content .= '<tr> <th scope="row" colspan="2"> <font align="left">Tax:</font> </th> <td> <font align="left"> <span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_cart_tax() + $wooCommerceOrderObject->get_shipping_tax()) . '</span> </font> </td> </tr> <tr> <th scope="row" colspan="2"> <font align="left">Shipping:</font> </th> <td> <font align="left"> <span class="amount">$' . $wooCommerceOrderObject->get_total_shipping() . '</span> <small>via ' . $wooCommerceOrderObject->get_shipping_method() . '</small> </font> </td> </tr> <tr> <th scope="row" colspan="2"> <font align="left">Payment Method:</font> </th> <td> <font align="left">' . $wooCommerceOrderObject->payment_method_title . '</font> </td> </tr> <tr> <th scope="row" colspan="2"> <font align="left">Order Total:</font> </th> <td> <font align="left"> <span class="amount">$' . sprintf('%0.2f', $wooCommerceOrderObject->get_total()) . '</span> </font> </td> </tr> </tfoot> </table> <h2> <font face="Arial" align="left" style="font-weight:bold;font-size:30px;color:#6d6d6d">Customer details</font> </h2> <p><strong>Email:</strong> ' . $customerMailId . '</p> <p><strong>Tel:</strong> ' . $wooCommerceOrderObject->billing_phone . '</p> <table cellspacing="0" cellpadding="0" border="0"> <tbody> <tr> <td valign="top" width="50%"> <h3> <font face="Arial" align="left" style="font-weight:bold;font-size:26px;color:#6d6d6d">Billing address</font> </h3> <p>' . $wooCommerceOrderObject->get_formatted_billing_address() . '</p> </td> <td valign="top" width="50%"> <h3> <font face="Arial" align="left" style="font-weight:bold;font-size:26px;color:#6d6d6d">Shipping address</font> </h3> <p>' . $wooCommerceOrderObject->get_formatted_shipping_address() . '</p> </td> </tr> </tbody> </table> </font> </div> </td> </tr> </tbody> </table> </font> </td> </tr> </tbody> </table> </td> </tr> <tr> <td align="center" valign="top"> <table border="0" cellpadding="10" cellspacing="0" width="600" id="template_footer"> <tbody> <tr> <td valign="top"> <table border="0" cellpadding="4" cellspacing="0" width="100%"> <tbody> <tr> <td colspan="2" valign="middle" id="credit" style="background-color: #777;"> <font face="Arial" align="center" style="font-size:12px;color:#bce3de"> <p>' . site_url() . '</p> </font> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table> </td> </tr> </tbody> </table>'; $emailHeader = "Content-type: text/html"; // To send HTML mail, the Content-type header must be set $emailHeader = 'MIME-Version: 1.0' . "\r\n"; $emailHeader .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; // Additional emailHeader $emailHeader .= 'From: ' . get_bloginfo('name') . ' <*****@*****.**>' . "\r\n"; $emailSubject = "Your plexuser order receipt from " . date_i18n(wc_date_format(), strtotime($wooCommerceOrderObject->order_date)); wp_mail($customerMailId, $emailSubject, $invoice_mail_content, $emailHeader); }
/** * Process the payment and return the result **/ function process_payment($order_id) { global $woocommerce; require_once "alipay_config.php"; require_once "class/alipay_service.php"; $order = new WC_Order($order_id); if (sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $item) { if ($item['qty']) { $item_names[] = $item['name'] . ' x ' . $item['qty']; } } } //扩展功能参数——默认支付方式 $paymethod = "directPay"; //默认支付方式,四个值可选:bankPay(网银); cartoon(卡通); directPay(余额); CASH(网点支付) $defaultbank = ""; //扩展功能参数——防钓鱼 //请慎重选择是否开启防钓鱼功能 //exter_invoke_ip、anti_phishing_key一旦被使用过,那么它们就会成为必填参数 //开启防钓鱼功能后,服务器、本机电脑必须支持远程XML解析,请配置好该环境。 //若要使用防钓鱼功能,请打开class文件夹中alipay_function.php文件,找到该文件最下方的query_timestamp函数,根据注释对该函数进行修改 //建议使用POST方式请求数据 $anti_phishing_key = ''; //防钓鱼时间戳 $exter_invoke_ip = ''; //获取客户端的IP地址,建议:编写获取客户端IP地址的程序 //如: //$exter_invoke_ip = '202.1.1.1'; //$anti_phishing_key = query_timestamp($partner); //获取防钓鱼时间戳函数 //扩展功能参数——其他 $extra_common_param = ''; //自定义参数,可存放任何内容(除=、&等特殊字符外),不会显示在页面上 $buyer_email = ''; //默认买家支付宝账号 //扩展功能参数——分润(若要使用,请按照注释要求的格式赋值) $royalty_type = ""; //提成类型,该值为固定值:10,不需要修改 $royalty_parameters = ""; //提成信息集,与需要结合商户网站自身情况动态获取每笔交易的各分润收款账号、各分润金额、各分润说明。最多只能设置10条 //各分润金额的总和须小于等于total_fee //提成信息集格式为:收款方Email_1^金额1^备注1|收款方Email_2^金额2^备注2 //如: //royalty_type = "10" //royalty_parameters = "111@126.com^0.01^分润备注一|222@126.com^0.01^分润备注二" ///////////////////////////////////////////////// //构造要请求的参数数组,无需改动 $parameter = array("service" => "create_direct_pay_by_user", "payment_type" => "1", "partner" => $partner, "seller_email" => $seller_email, "return_url" => $return_url, "notify_url" => $notify_url, "_input_charset" => $_input_charset, "show_url" => get_bloginfo('wpurl'), "out_trade_no" => 'CIP' . $order_id, "subject" => implode(',', $item_names), "body" => implode(',', $item_names), "total_fee" => number_format($order->get_order_total() - $order->get_total_discount(), 2, '.', ''), "paymethod" => $paymethod, "defaultbank" => $defaultbank, "anti_phishing_key" => $anti_phishing_key, "exter_invoke_ip" => $exter_invoke_ip, "buyer_email" => $buyer_email, "extra_common_param" => $extra_common_param, "royalty_type" => $royalty_type, "royalty_parameters" => $royalty_parameters); //构造请求函数 $alipay = new alipay_service($parameter, $key, $sign_type); $sHtmlText = $alipay->build_form(); $html = "<html>\r\n\t\t\t<head>\r\n\t\t\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n\t\t\t\t<title>正在前往支付宝...</title>\r\n\t\t\t</head>\r\n\t\t\t<body><div style='display:none'>{$sHtmlText}</div"; echo $html; exit; return array('result' => 'success', 'redirect' => $sHtmlText); }
/** * 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'); } }
/** * Process the payment and return the result **/ function process_payment($order_id) { global $woocommerce; require_once "classes/RequestHandler.class.php"; $order = new WC_Order($order_id); if (sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $item) { if ($item['qty']) { $item_names[] = $item['name'] . ' x ' . $item['qty']; } } } ////////////////////////////// /* 商户号 */ $partner = $this->tenpayUid; /* 密钥 */ $key = $this->tenpayKey; //订单号,此处用时间加随机数生成,商户根据自己情况调整,只要保持全局唯一就行 $out_trade_no = 'CIP' . $order_id; /* 创建支付请求对象 */ $reqHandler = new RequestHandler(); $reqHandler->init(); $reqHandler->setKey($key); $reqHandler->setGateUrl("https://gw.tenpay.com/gateway/pay.htm"); //---------------------------------------- //设置支付参数 //---------------------------------------- $reqHandler->setParameter("partner", $partner); $reqHandler->setParameter("out_trade_no", $out_trade_no); $reqHandler->setParameter("total_fee", ($order->get_order_total() - $order->get_total_discount()) * 100); //总金额 $reqHandler->setParameter("return_url", CI_WC_ALI_PATH . "/payReturnUrl.php"); $reqHandler->setParameter("notify_url", CI_WC_ALI_PATH . "/payNotifyUrl.php"); $reqHandler->setParameter("body", implode(',', $item_names)); $reqHandler->setParameter("bank_type", "DEFAULT"); //银行类型,默认为财付通 //用户ip $reqHandler->setParameter("spbill_create_ip", $_SERVER['REMOTE_ADDR']); //客户端IP $reqHandler->setParameter("fee_type", "1"); //币种 $reqHandler->setParameter("subject", ''); //商品名称,(中介交易时必填) //系统可选参数 $reqHandler->setParameter("sign_type", "MD5"); //签名方式,默认为MD5,可选RSA $reqHandler->setParameter("service_version", "1.0"); //接口版本号 $reqHandler->setParameter("input_charset", "UTF-8"); //字符集 $reqHandler->setParameter("sign_key_index", "1"); //密钥序号 //业务可选参数 $reqHandler->setParameter("attach", ""); //附件数据,原样返回就可以了 $reqHandler->setParameter("product_fee", ""); //商品费用 $reqHandler->setParameter("transport_fee", "0"); //物流费用 $reqHandler->setParameter("time_start", date("YmdHis")); //订单生成时间 $reqHandler->setParameter("time_expire", ""); //订单失效时间 $reqHandler->setParameter("buyer_id", ""); //买方财付通帐号 $reqHandler->setParameter("goods_tag", ""); //商品标记 $reqHandler->setParameter("trade_mode", "1"); //交易模式(1.即时到帐模式,2.中介担保模式,3.后台选择(卖家进入支付中心列表选择)) $reqHandler->setParameter("transport_desc", ""); //物流说明 $reqHandler->setParameter("trans_type", "1"); //交易类型 $reqHandler->setParameter("agentid", ""); //平台ID $reqHandler->setParameter("agent_type", ""); //代理模式(0.无代理,1.表示卡易售模式,2.表示网店模式) $reqHandler->setParameter("seller_id", ""); //卖家的商户号 $reqUrl = $reqHandler->getRequestURL(); $html_text = ' <script>window.location.href="' . $reqUrl . '"</script>'; //param end $output = "\r\n\t\t\t<html>\r\n\t\t <head>\r\n\t\t\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n\t\t <title>正在前往财付通...</title>\r\n\t\t </head>\r\n\t\t <body>{$html_text}</body></html>"; echo $output; exit; return array('result' => 'success', 'redirect' => $output); }
/** * Process the payment and return the result **/ function process_payment($order_id) { global $woocommerce; $order = new WC_Order($order_id); if (sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $item) { if ($item['qty']) { $item_names[] = $item['name'] . ' x ' . $item['qty']; } } } // $v_mid = $this->bankUid; // 商户号,这里为测试商户号1001,替换为自己的商户号(老版商户号为4位或5位,新版为8位)即可 $v_url = CI_WC_ALI_PATH . '/chinabank/receive.php'; // 请填写返回url,地址应为绝对路径,带有http协议 $key = $this->bankKey; $v_oid = 'CIP' . $order_id; $v_amount = number_format($order->get_order_total() - $order->get_total_discount(), 2, '.', ''); //支付金额 $v_moneytype = "CNY"; //币种 $text = $v_amount . $v_moneytype . $v_oid . $v_mid . $v_url . $key; //md5加密拼凑串,注意顺序不能变 $v_md5info = strtoupper(md5($text)); //md5函数加密并转化成大写字母 $remark1 = ''; //备注字段1 $remark2 = ''; //备注字段2 $v_rcvname = ''; // 收货人 $v_rcvaddr = ''; // 收货地址 $v_rcvtel = ''; // 收货人电话 $v_rcvpost = ''; // 收货人邮编 $v_rcvemail = ''; // 收货人邮件 $v_rcvmobile = ''; // 收货人手机号 $v_ordername = ''; // 订货人姓名 $v_orderaddr = ''; // 订货人地址 $v_ordertel = ''; // 订货人电话 $v_orderpost = ''; // 订货人邮编 $v_orderemail = ''; // 订货人邮件 $v_ordermobile = ''; // 订货人手机号 $html_text = ' <form method="post" name="E_FORM" action="https://pay3.chinabank.com.cn/PayGate"> <input type="hidden" name="v_mid" value="' . $v_mid . '"> <input type="hidden" name="v_oid" value="' . $v_oid . '"> <input type="hidden" name="v_amount" value="' . $v_amount . '"> <input type="hidden" name="v_moneytype" value="' . $v_moneytype . '"> <input type="hidden" name="v_url" value="' . $v_url . '"> <input type="hidden" name="v_md5info" value="' . $v_md5info . '"> <input type="hidden" name="remark1" value="' . $remark1 . '"> <input type="hidden" name="remark2" value="' . $remark2 . '"> </form> <script>document.E_FORM.submit();</script>'; $output = "\r\n\t\t\t<html>\r\n\t\t <head>\r\n\t\t\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n\t\t <title>正在前往网银在线...</title>\r\n\t\t </head>\r\n\t\t <body><div style='display:none'>{$html_text}</div>'</body></html>"; echo $output; exit; return array('result' => 'success', 'redirect' => $output); }
/** * Set up the payment details for a DoExpressCheckoutPayment or DoReferenceTransaction request * * @since 2.0.9 * @param WC_Order $order order object * @param string $type the type of transaction for the payment * @param bool $use_deprecated_params whether to use deprecated PayPal NVP parameters (required for DoReferenceTransaction API calls) */ protected function add_payment_details_parameters(WC_Order $order, $type, $use_deprecated_params = false) { $calculated_total = 0; $order_subtotal = 0; $item_count = 0; $order_items = array(); // add line items foreach ($order->get_items() as $item) { $product = new WC_Product($item['product_id']); $order_items[] = array('NAME' => wcs_get_paypal_item_name($product->get_title()), 'DESC' => $this->get_item_description($item, $product), 'AMT' => $this->round($order->get_item_subtotal($item)), 'QTY' => !empty($item['qty']) ? absint($item['qty']) : 1, 'ITEMURL' => $product->get_permalink()); $order_subtotal += $item['line_total']; } // add fees foreach ($order->get_fees() as $fee) { $order_items[] = array('NAME' => wcs_get_paypal_item_name($fee['name']), 'AMT' => $this->round($fee['line_total']), 'QTY' => 1); $order_subtotal += $fee['line_total']; } // add discounts if ($order->get_total_discount() > 0) { $order_items[] = array('NAME' => __('Total Discount', 'woocommerce-subscriptions'), 'QTY' => 1, 'AMT' => -$this->round($order->get_total_discount())); } if ($this->skip_line_items($order)) { $total_amount = $this->round($order->get_total()); // calculate the total as PayPal would $calculated_total += $this->round($order_subtotal + $order->get_cart_tax()) + $this->round($order->get_total_shipping() + $order->get_shipping_tax()); // offset the discrepency between the WooCommerce cart total and PayPal's calculated total by adjusting the order subtotal if ($total_amount !== $calculated_total) { $order_subtotal = $order_subtotal - ($calculated_total - $total_amount); } $item_names = array(); foreach ($order_items as $item) { $item_names[] = sprintf('%1$s x %2$s', $item['NAME'], $item['QTY']); } // add a single item for the entire order $this->add_line_item_parameters(array('NAME' => sprintf(__('%s - Order', 'woocommerce-subscriptions'), get_option('blogname')), 'DESC' => wcs_get_paypal_item_name(implode(', ', $item_names)), 'AMT' => $this->round($order_subtotal + $order->get_cart_tax()), 'QTY' => 1), 0, $use_deprecated_params); // add order-level parameters // - Do not sent the TAXAMT due to rounding errors if ($use_deprecated_params) { $this->add_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal + $order->get_cart_tax()), 'SHIPPINGAMT' => $this->round($order->get_total_shipping() + $order->get_shipping_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key)))); } else { $this->add_payment_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal + $order->get_cart_tax()), 'SHIPPINGAMT' => $this->round($order->get_total_shipping() + $order->get_shipping_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key)))); } } else { // add individual order items foreach ($order_items as $item) { $this->add_line_item_parameters($item, $item_count++, $use_deprecated_params); $calculated_total += $this->round($item['AMT'] * $item['QTY']); } // add shipping and tax to calculated total $calculated_total += $this->round($order->get_total_shipping()) + $this->round($order->get_total_tax()); $total_amount = $this->round($order->get_total()); // add order-level parameters if ($use_deprecated_params) { $this->add_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal), 'SHIPPINGAMT' => $this->round($order->get_total_shipping()), 'TAXAMT' => $this->round($order->get_total_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key)))); } else { $this->add_payment_parameters(array('AMT' => $total_amount, 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $this->round($order_subtotal), 'SHIPPINGAMT' => $this->round($order->get_total_shipping()), 'TAXAMT' => $this->round($order->get_total_tax()), 'INVNUM' => WCS_PayPal::get_option('invoice_prefix') . wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number. Used as a character to remove from the actual order number', 'woocommerce-subscriptions'))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id, 'CUSTOM' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key)))); } // offset the discrepency between the WooCommerce cart total and PayPal's calculated total by adjusting the cost of the first item if ($total_amount !== $calculated_total) { $this->parameters['L_PAYMENTREQUEST_0_AMT0'] = $this->parameters['L_PAYMENTREQUEST_0_AMT0'] - ($calculated_total - $total_amount); } } }
/** * 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) { $ms = sprintf(__('Sorry, your session has expired. <a href=%s>Return to homepage →</a>', 'paypal-for-woocommerce'), '"' . home_url() . '"'); $ec_confirm_message = apply_filters('angelleye_ec_confirm_message', $ms); wc_add_notice($ec_confirm_message, "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' => $this->payment_action == 'Authorization' ? 'Authorization' : 'Sale', 'paymentrequestid' => '', 'sellerpaypalaccountid' => '', 'sellerid' => '', 'sellerusername' => '', 'sellerregistrationdate' => '', 'softdescriptor' => ''); $PaymentOrderItems = array(); $ctr = $total_items = $total_discount = $total_tax = $shipping = 0; $ITEMAMT = 0; if (sizeof($order->get_items()) > 0) { if ($this->send_items) { 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); } } $Item = array('name' => $values['name'], 'desc' => '', 'amt' => round($values['line_subtotal'] / $qty, 2), 'number' => $sku, 'qty' => $qty, 'taxamt' => '', 'itemurl' => '', 'itemcategory' => '', 'itemweightvalue' => '', 'itemweightunit' => '', 'itemheightvalue' => '', 'itemheightunit' => '', 'itemwidthvalue' => '', 'itemwidthunit' => '', 'itemlengthvalue' => '', 'itemlengthunit' => '', 'ebayitemnumber' => '', 'ebayitemauctiontxnid' => '', 'ebayitemorderid' => '', 'ebayitemcartid' => ''); array_push($PaymentOrderItems, $Item); $ITEMAMT += round($values['line_subtotal'] / $qty, 2) * $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++; } if (!$this->is_wc_version_greater_2_3()) { /* * 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); } $total_discount -= $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); } $total_discount -= $order->get_order_discount(); } } else { if ($order->get_total_discount() > 0) { $Item = array('name' => 'Total Discount', 'qty' => 1, 'amt' => -number_format($order->get_total_discount(), 2, '.', '')); array_push($PaymentOrderItems, $Item); $total_discount -= $order->get_total_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(); } if ('yes' === get_option('woocommerce_calc_taxes') && 'yes' === get_option('woocommerce_prices_include_tax')) { $tax = $order->get_total_tax(); } if ($tax > 0) { $tax = number_format($tax, 2, '.', ''); } if ($shipping > 0) { $shipping = number_format($shipping, 2, '.', ''); } if ($total_discount) { $total_discount = round($total_discount, 2); } if ($this->send_items) { /* * Now that we have all items and subtotals * we can fill in necessary values. */ $Payment['itemamt'] = number_format($ITEMAMT + $total_discount, 2, '.', ''); } else { $PaymentOrderItems = array(); $Payment['itemamt'] = number_format($ITEMAMT + $total_discount, 2, '.', ''); } /* * 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); // Rounding amendment if (trim(number_format(WC()->cart->total, 2, '.', '')) !== trim(number_format($Payment['itemamt'] + number_format($tax, 2, '.', '') + number_format($shipping, 2, '.', ''), 2, '.', ''))) { $diffrence_amount = $this->get_diffrent(WC()->cart->total, $Payment['itemamt'] + $tax + number_format($shipping, 2, '.', '')); if ($shipping > 0) { $PayPalRequestData['Payments'][0]['shippingamt'] = round($shipping + $diffrence_amount, 2); } elseif ($tax > 0) { $PayPalRequestData['Payments'][0]['taxamt'] = round($tax + $diffrence_amount, 2); } else { $PayPalRequestData['Payments'][0]['itemamt'] = round($PayPalRequestData['Payments'][0]['itemamt'] + $diffrence_amount, 2); } } // 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; }
/** * Charge a payment against a reference token * * @link https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECReferenceTxns/#id094UM0DA0HS * @link https://developer.paypal.com/docs/classic/api/merchant/DoReferenceTransaction_API_Operation_NVP/ * * @param string $reference_id the ID of a refrence object, e.g. billing agreement ID. * @param WC_Order $order order object * @param array $args { * @type string 'payment_type' (Optional) Specifies type of PayPal payment you require for the billing agreement. It is one of the following values. 'Any' or 'InstantOnly'. Echeck is not supported for DoReferenceTransaction requests. * @type string 'payment_action' How you want to obtain payment. It is one of the following values: 'Authorization' - this payment is a basic authorization subject to settlement with PayPal Authorization and Capture; or 'Sale' - This is a final sale for which you are requesting payment. * @type string 'return_fraud_filters' (Optional) Flag to indicate whether you want the results returned by Fraud Management Filters. By default, you do not receive this information. * } * @since 2.0 */ public function do_reference_transaction($reference_id, $order, $args = array()) { $defaults = array('amount' => $order->get_total(), 'payment_type' => 'Any', 'payment_action' => 'Sale', 'return_fraud_filters' => 1, 'notify_url' => WC()->api_request_url('WC_Gateway_Paypal'), 'invoice_number' => wcs_str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number', 'woocommerce-subscriptions'))), 'custom' => json_encode(array('order_id' => $order->id, 'order_key' => $order->order_key))); $args = wp_parse_args($args, $defaults); $this->set_method('DoReferenceTransaction'); // set base params $this->add_parameters(array('REFERENCEID' => $reference_id, 'BUTTONSOURCE' => 'WooThemes_Cart', 'RETURNFMFDETAILS' => $args['return_fraud_filters'], 'AMT' => $order->get_total(), 'CURRENCYCODE' => $order->get_order_currency(), 'INVNUM' => $args['invoice_number'], 'PAYMENTACTION' => $args['payment_action'], 'NOTIFYURL' => $args['notify_url'], 'CUSTOM' => $args['custom'])); $order_subtotal = $i = 0; $order_items = array(); // add line items foreach ($order->get_items() as $item) { $order_items[] = array('NAME' => wcs_get_paypal_item_name($item['name']), 'AMT' => $order->get_item_subtotal($item), 'QTY' => !empty($item['qty']) ? absint($item['qty']) : 1); $order_subtotal += $item['line_total']; } // add fees foreach ($order->get_fees() as $fee) { $order_items[] = array('NAME' => wcs_get_paypal_item_name($fee['name']), 'AMT' => $fee['line_total'], 'QTY' => 1); $order_subtotal += $fee['line_total']; } // WC 2.3+, no after-tax discounts if ($order->get_total_discount() > 0) { $order_items[] = array('NAME' => __('Total Discount', 'woocommerce-subscriptions'), 'QTY' => 1, 'AMT' => -$order->get_total_discount()); } if ($order->prices_include_tax) { $item_names = array(); foreach ($order_items as $item) { $item_names[] = sprintf('%s x %s', $item['NAME'], $item['QTY']); } // add a single item for the entire order $this->add_line_item_parameters(array('NAME' => sprintf(__('%s - Order', 'woocommerce-subscriptions'), get_option('blogname')), 'DESC' => wcs_get_paypal_item_name(implode(', ', $item_names)), 'AMT' => $order_subtotal + $order->get_cart_tax(), 'QTY' => 1), 0); // add order-level parameters - do not send the TAXAMT due to rounding errors $this->add_payment_parameters(array('ITEMAMT' => $order_subtotal + $order->get_cart_tax(), 'SHIPPINGAMT' => $order->get_total_shipping() + $order->get_shipping_tax())); } else { // add individual order items foreach ($order_items as $item) { $this->add_line_item_parameters($item, $i++); } // add order-level parameters $this->add_payment_parameters(array('ITEMAMT' => $order_subtotal, 'SHIPPINGAMT' => $order->get_total_shipping(), 'TAXAMT' => $order->get_total_tax())); } }
/** * After the payment method and validation data from transparent-checkout.php this method is called * to send the real payment information to gerencianet * * Also this method handle with notifications of any status of the payment * * @param array $posted gerencianet post data. * * @return void */ public function successful_request($posted) { //If the IPN request is about notification if (!empty($posted['notificacao'])) { try { include_once 'gerencianet-api/ApiCheckoutGerencianet.php'; $url = 'https://go.gerencianet.com.br/api/notificacao/xml'; $apiGerenciaNet = new ApiCheckoutGerencianet($url); $token = $this->token; $notification_code = $posted['notificacao']; $parametros = array($notification_code => 'notificacao'); $result = $apiGerenciaNet->consultarStatusPagamento($parametros, $token); $result = simplexml_load_string($result); $order = new WC_Order($result->resposta->identificador); if (!empty($order)) { $status = $result->resposta->status; switch ($status) { case 'aguardando': $order->update_status('pending', __('Waiting Payment nº ') . $result->resposta->transacao); break; case 'pago': $order->update_status('completed', __('All payment process completed transaction nº ') . $result->resposta->transacao); break; case 'cancelado': $order->update_status('cancelled', __('Order cancelled transaction nº ') . $result->resposta->transacao); break; case 'vencido': $order->update_status('failed', __('Order failed transaction nº ') . $result->resposta->transacao); break; default: //no action break; } if ('yes' == $this->debug) { $this->log->add('gerencianet', 'changing status order ' . $order->get_order_number()); } } else { if ('yes' == $this->debug) { $this->log->add('gerencianet', 'changing status order error ' . $e->getMessage()); } } } catch (Exception $e) { if ('yes' == $this->debug) { $this->log->add('gerencianet', 'changing status order error ' . $e->getMessage()); } } exit; } //if the IPN request is about payment if (!empty($posted['tokenPagamento'])) { try { include_once 'gerencianet-api/ApiCheckoutGerencianet.php'; $order = new WC_Order($posted['outros']['wc_order_id']); // Payment URL or Sandbox URL. $payment_url = 'https://go.gerencianet.com.br/api/checkout/pagar/xml'; if ('yes' == $this->sandbox) { $payment_url = 'https://go.gerencianet.com.br/teste/api/checkout/pagar/xml'; } $apiGerenciaNet = new ApiCheckoutGerencianet($payment_url); $token = $this->token; $tokenPagamento = $posted['tokenPagamento']; $order_items = $order->get_items(); $items = array(); foreach ($order_items as $items_key => $item) { $items[] = array("itemDescricao" => $item['name'], "itemValor" => $this->price_cents_format($item['line_total'] / $item['qty']), "itemQuantidade" => $item['qty']); } $retorno = array('identificador' => $posted['outros']['wc_order_id'], 'urlNotificacao' => home_url('/?wc-api=WC_Gerencianet')); $client = $posted['cliente']; $enderecoEntrega = $posted['enderecoEntrega']; //forma de entrega $formaEntrega = array(); if ($posted['metodo'] == 'boleto') { $date = $order->order_date; $date = date_create($date); date_add($date, date_interval_create_from_date_string($this->billet_number_days . ' days')); $formaEntrega['boleto'] = array('vencimento' => date_format($date, 'Y-m-d')); } else { if ($posted['metodo'] == 'cartao-credito') { $parcelas = $posted['formaPagamento']['cartao']['parcelas']; $formaEntrega['cartao'] = array('parcelas' => $parcelas, 'enderecoCobranca' => $enderecoEntrega); } } $parametros = array('itens' => $items, 'retorno' => $retorno, 'desconto' => $this->price_cents_format($order->get_total_discount()), 'frete' => $this->price_cents_format($order->get_total_shipping()), 'tipo' => 'produto', 'cliente' => $client, 'enderecoEntrega' => $enderecoEntrega, 'formaPagamento' => $formaEntrega); $result = $apiGerenciaNet->pagar($parametros, $token, $tokenPagamento); $result = simplexml_load_string($result); $result->redirect = $posted['outros']['wc_redirect']; $result->tokenPagamento = $tokenPagamento; echo json_encode($result); if ('yes' == $this->debug) { $this->log->add('gerencianet', 'Sending payment ' . print_r($parametros, true) . ' token =>' . $token . ' tokenPagamento => ' . $tokenPagamento); } } catch (Exception $e) { if ('yes' == $this->debug) { $this->log->add('gerencianet', 'Sending payment error ' . $e->getMessage()); } } exit; } }
function bp_course_enable_access($order_id) { $order = new WC_Order($order_id); $items = $order->get_items(); $user_id = $order->user_id; $order_total = $order->get_total(); $total_discount = $order->get_total_discount(); $commission_array = array(); foreach ($items as $item_id => $item) { $instructors = array(); $product_id = $item['product_id']; $subscribed = get_post_meta($product_id, 'vibe_subscription', true); $courses = vibe_sanitize(get_post_meta($product_id, 'vibe_courses', false)); if ($total_discount) { $multiplier = round($order_total / ($order_total + $total_discount), 4); } if (isset($courses) && is_array($courses)) { if (vibe_validate($subscribed)) { $duration = get_post_meta($product_id, 'vibe_duration', true); $product_duration_parameter = apply_filters('vibe_product_duration_parameter', 86400); // Product duration for subscription based foreach ($courses as $course) { $start_date = get_post_meta($course, 'vibe_start_date', true); $time = 0; if (isset($start_date) && $start_date) { $time = strtotime($start_date); } if ($time < time()) { $time = time(); } $t = $time + $duration * $product_duration_parameter; update_post_meta($course, $user_id, 0); update_user_meta($user_id, $course, $t); update_user_meta($user_id, 'course_status' . $course, 1); $group_id = get_post_meta($course, 'vibe_group', true); if (isset($group_id) && $group_id != '' && is_numeric($group_id) && function_exists('groups_join_group')) { groups_join_group($group_id, $user_id); } else { $group_id = ''; } $durationtime = $duration . ' ' . calculate_duration_time($product_duration_parameter); if ($duration == '9999') { $durationtime = __('Unlimited Duration', 'vibe'); } do_action('wplms_course_subscribed', $course, $user_id, $group_id); $instructors[$course] = apply_filters('wplms_course_instructors', get_post_field('post_author', $course), $course); do_action('wplms_course_product_puchased', $course, $user_id, $t, 1); } } else { if (isset($courses) && is_array($courses)) { foreach ($courses as $course) { $duration = get_post_meta($course, 'vibe_duration', true); $course_duration_parameter = apply_filters('vibe_course_duration_parameter', 86400); // Course duration for subscription based $start_date = get_post_meta($course, 'vibe_start_date', true); $time = 0; if (isset($start_date) && $start_date) { $time = strtotime($start_date); } if ($time < time()) { $time = time(); } $t = $time + $duration * $course_duration_parameter; update_post_meta($course, $user_id, 0); update_user_meta($user_id, $course, $t); update_user_meta($user_id, 'course_status' . $course, 1); $group_id = get_post_meta($course, 'vibe_group', true); if (isset($group_id) && $group_id != '' && is_numeric($group_id) && function_exists('groups_join_group')) { groups_join_group($group_id, $user_id); } else { $group_id = ''; } $durationtime = $duration . ' ' . calculate_duration_time($product_duration_parameter); if ($duration == '9999') { $durationtime = __('Unlimited Duration', 'vibe'); } do_action('wplms_course_subscribed', $course, $user_id, $group_id); $instructors[$course] = apply_filters('wplms_course_instructors', get_post_field('post_author', $course, 'raw'), $course); do_action('wplms_course_product_puchased', $course, $user_id, $t, 0); } } } //End Else if ($total_discount) { // Product discounted $line_total = round($item['line_total'] * $multiplier, 2); } else { $line_total = $item['line_total']; } //Commission Calculation $commission_array[$item_id] = array('instructor' => $instructors, 'course' => $courses, 'total' => $line_total); } //End If courses } // End Item for loop if (function_exists('vibe_get_option')) { $instructor_commission = vibe_get_option('instructor_commission'); } if ($instructor_commission == 0) { return; } if (!isset($instructor_commission) || !$instructor_commission) { $instructor_commission = 70; } $commissions = get_option('instructor_commissions'); foreach ($commission_array as $item_id => $commission_item) { foreach ($commission_item['course'] as $course_id) { if (count($commission_item['instructor'][$course_id]) > 1) { // Multiple instructors $calculated_commission_base = round($commission_item['total'] * ($instructor_commission / 100) / count($commission_item['instructor'][$course_id]), 0); // Default Slit equal propertion foreach ($commission_item['instructor'][$course_id] as $instructor) { if (isset($commissions[$course_id][$instructor])) { $calculated_commission_base = round($commission_item['total'] * $commissions[$course_id][$instructor] / 100, 2); } $calculated_commission_base = apply_filters('wplms_calculated_commission_base', $calculated_commission_base, $instructor); woocommerce_update_order_item_meta($item_id, 'commission' . $instructor, $calculated_commission_base); } } else { if (is_array($commission_item['instructor'][$course_id])) { // Single Instructor $instructor = $commission_item['instructor'][$course_id][0]; } else { $instructor = $commission_item['instructor'][$course_id]; } if (isset($commissions[$course_id][$instructor]) && is_numeric($commissions[$course_id][$instructor])) { $calculated_commission_base = round($commission_item['total'] * $commissions[$course_id][$instructor] / 100, 2); } else { $calculated_commission_base = round($commission_item['total'] * $instructor_commission / 100, 2); } $calculated_commission_base = apply_filters('wplms_calculated_commission_base', $calculated_commission_base, $instructor); woocommerce_update_order_item_meta($item_id, 'commission' . $instructor, $calculated_commission_base); } } } // End Commissions_array }
/** * Set up the DoExpressCheckoutPayment request * * @link https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECGettingStarted/#id084RN060BPF * @link https://developer.paypal.com/webapps/developer/docs/classic/api/merchant/DoExpressCheckoutPayment_API_Operation_NVP/ * * @since 3.0.0 * @param \WC_Order $order order object * @param string $type */ private function do_payment(WC_Order $order, $type) { $this->set_method('DoExpressCheckoutPayment'); // set base params $this->add_parameters(array('TOKEN' => $order->paypal_express_token, 'PAYERID' => !empty($order->paypal_express_payer_id) ? $order->paypal_express_payer_id : null, 'BUTTONSOURCE' => 'WooThemes_Cart', 'RETURNFMFDETAILS' => 1)); $order_subtotal = $i = 0; $order_items = array(); // add line items foreach ($order->get_items() as $item) { $product = new WC_Product($item['product_id']); $order_items[] = array('NAME' => SV_WC_Helper::str_truncate(html_entity_decode($product->get_title(), ENT_QUOTES, 'UTF-8'), 127), 'DESC' => $this->get_item_description($item, $product), 'AMT' => $order->get_item_subtotal($item), 'QTY' => !empty($item['qty']) ? absint($item['qty']) : 1, 'ITEMURL' => $product->get_permalink()); $order_subtotal += $item['line_total']; } // add fees foreach ($order->get_fees() as $fee) { $order_items[] = array('NAME' => SV_WC_Helper::str_truncate($fee['name'], 127), 'AMT' => $fee['line_total'], 'QTY' => 1); $order_subtotal += $fee['line_total']; } if (SV_WC_Plugin_Compatibility::is_wc_version_gte_2_3()) { // WC 2.3+, no after-tax discounts if ($order->get_total_discount() > 0) { $order_items[] = array('NAME' => __('Total Discount', WC_Paypal_Express::TEXT_DOMAIN), 'QTY' => 1, 'AMT' => -$order->get_total_discount()); } } else { // WC 2.2 or lesser // add cart discounts as line item if ($order->get_cart_discount() > 0) { $order_items[] = array('NAME' => __('Cart Discount', WC_Paypal_Express::TEXT_DOMAIN), 'QTY' => 1, 'AMT' => -$order->get_cart_discount()); } // add order discounts as line item if ($order->get_order_discount() > 0) { $order_items[] = array('NAME' => __('Order Discount', WC_Paypal_Express::TEXT_DOMAIN), 'QTY' => 1, 'AMT' => -$order->get_order_discount()); } } $total_discount = SV_WC_Plugin_Compatibility::is_wc_version_gte_2_3() ? 0 : $order->get_order_discount(); // order subtotal includes pre-tax discounts in 2.3 if ($this->skip_line_items($order)) { $item_names = array(); foreach ($order_items as $item) { $item_names[] = sprintf('%s x %s', $item['NAME'], $item['QTY']); } // add a single item for the entire order $this->add_line_item_parameters(array('NAME' => sprintf(__('%s - Order', WC_PayPal_Express::TEXT_DOMAIN), get_option('blogname')), 'DESC' => SV_WC_Helper::str_truncate(html_entity_decode(implode(', ', $item_names), ENT_QUOTES, 'UTF-8'), 127), 'AMT' => $order_subtotal - $total_discount + $order->get_cart_tax(), 'QTY' => 1), 0); // add order-level parameters // - Do not sent the TAXAMT due to rounding errors $this->add_payment_parameters(array('AMT' => $order->get_total(), 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $order_subtotal - $total_discount + $order->get_cart_tax(), 'SHIPPINGAMT' => $order->get_total_shipping() + $order->get_shipping_tax(), 'INVNUM' => $order->paypal_express_invoice_prefix . SV_WC_Helper::str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number', WC_PayPal_Express::TEXT_DOMAIN))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id)); } else { // add individual order items foreach ($order_items as $item) { $this->add_line_item_parameters($item, $i++); } // add order-level parameters $this->add_payment_parameters(array('AMT' => $order->get_total(), 'CURRENCYCODE' => $order->get_order_currency(), 'ITEMAMT' => $order_subtotal - $total_discount, 'SHIPPINGAMT' => $order->get_total_shipping(), 'TAXAMT' => $order->get_total_tax(), 'INVNUM' => $order->paypal_express_invoice_prefix . SV_WC_Helper::str_to_ascii(ltrim($order->get_order_number(), _x('#', 'hash before the order number', WC_PayPal_Express::TEXT_DOMAIN))), 'PAYMENTACTION' => $type, 'PAYMENTREQUESTID' => $order->id)); } }
/** * Test: get_total_discount */ function test_get_total_discount() { $object = new WC_Order(); $object->set_discount_total(50); $object->set_discount_tax(5); $this->assertEquals(50, $object->get_total_discount()); $this->assertEquals(55, $object->get_total_discount(false)); }
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); } } }
/** * Translate WooCommerce order into coinsimple invoice and POST invoice to coinsimple.com. * * @access public * @todo determine how to handle order statuses in this function. * @param string $order_id rendezvous token that identifies a WooCommerce order. * @param $reply passed by reference, returned if successful. * @return boolean true if successful or false if unsuccessful. */ public function post_invoice($order_id, &$reply) { $wc_order = new WC_Order($order_id); $invoice = new \CoinSimple\Invoice(); $invoice->setName($wc_order->billing_first_name . ' ' . $wc_order->billing_last_name); $invoice->setEmail($wc_order->billing_email); $invoice->setCurrency(strtolower(get_woocommerce_currency())); // create line items $wc_items = $wc_order->get_items(); foreach ($wc_items as $wc_item) { if (get_option('woocommerce_prices_include_tax') === 'yes') { $line_total = $wc_order->get_line_subtotal($wc_item, true, true); } else { $line_total = $wc_order->get_line_subtotal($wc_item, false, true); } $item = array("description" => $wc_item['name'], "quantity" => floatval($wc_item['qty']), "price" => round($line_total / $wc_item['qty'], 2)); $invoice->addItem($item); } $invoice->setNotes($this->get_option("notes")); //tax if ($wc_order->get_total_tax() != 0 && get_option('woocommerce_prices_include_tax') !== 'yes') { $tax = 0; foreach ($wc_order->get_tax_totals() as $value) { $tax += $value->amount; } $tax = round($tax, 2); $invoice->addItem(array("description" => "Sales tax", "quantity" => 1, "price" => $tax)); } // shipping if ($wc_order->get_total_shipping() != 0) { $shipping = $wc_order->get_total_shipping(); if (get_option('woocommerce_prices_include_tax') === 'yes') { $shipping += $wc_order->get_shipping_tax(); } $invoice->addItem(array("description" => "Shipping and handling", "quantity" => 1, "price" => round($shipping, 2))); } // coupens if ($wc_order->get_total_discount() != 0) { $invoice->addItem(array("description" => "Discounts", "quantity" => 1, "price" => -round($wc_order->get_total_discount(), 2))); } // settings part $invoice->setCallbackUrl(add_query_arg('wc-api', 'wc_coinsimple', home_url('/'))); $invoice->setCustom(array("order_id" => $wc_order->id, "order_key" => $wc_order->order_key)); if ($this->get_option("redirect_url") != "") { $invoice->setRedirectUrl($this->get_option("redirect_url")); } $business = new \CoinSimple\Business($this->get_option("business_id"), $this->get_option('api_key')); $res = $business->sendInvoice($invoice); if ($res->status == "ok") { $reply = $res; return true; } else { return false; } }
/** * Get discount. * * @param WC_Order $order * * @return int */ protected function get_discount($order) { if (defined('WC_VERSION') && version_compare(WC_VERSION, '2.3', '<')) { return $this->get_price($order->get_order_discount()); } else { return $this->get_price($order->get_total_discount()); } }
/** * Generate the payu button link * * @access public * @param mixed $order_id * @return string * * docs: http://docs.woothemes.com/wc-apidocs/class-WC_Order.html */ function generate_payu_form($order_id) { $order = new WC_Order($order_id); if ('yes' == $this->debug) { $this->log->add('payu', 'Generating payment form for order ' . $order->get_order_number() . '. Notify URL: ' . $this->notify_url); } require_once 'includes/payu.class.php'; $config = $this->get_payu_config($order->get_order_currency()); $lu = new PayULiveUpdate($config); if ($this->debug == 'yes') { $lu->logger = true; $lu->log_path = WC_LOG_DIR; } // általános megrendelési adatok $lu->setField("ORDER_REF", $order->id . '-' . time()); $lu->setField("ORDER_DATE", date("Y-m-d H:i:s")); $lu->setField("PRICES_CURRENCY", $order->get_order_currency()); $lu->setField("ORDER_PRICE_TYPE", "GROSS"); $lu->setField("PAY_METHOD", "CCVISAMC"); $lu->setField("DISCOUNT", round($order->get_total_discount(), 2)); $lu->setField("ORDER_TIMEOUT", "300"); $lu->setField("ORDER_SHIPPING", round($order->get_total_shipping() + $order->get_shipping_tax(), 2)); $lu->setField("LANGUAGE", strtoupper(substr(get_locale(), 0, 2))); // átirányítás, adatok feldogozása $lu->setField("BACK_REF", esc_url(add_query_arg(array('callback' => 'BACKREF'), $this->notify_url))); $lu->setField("TIMEOUT_URL", esc_url(add_query_arg(array('callback' => 'TIMEOUT'), $this->notify_url))); // számlázási adatok $lu->setField("BILL_FNAME", $order->billing_first_name); $lu->setField("BILL_LNAME", $order->billing_last_name); $lu->setField("BILL_COMPANY", $order->billing_company); $lu->setField("BILL_EMAIL", $order->billing_email); $lu->setField("BILL_PHONE", $this->payu_data_validation($order->billing_phone)); $lu->setField("BILL_ADDRESS", $this->payu_data_validation($order->billing_address_1)); $lu->setField("BILL_ADDRESS2", $order->billing_address_2); $lu->setField("BILL_ZIPCODE", $this->payu_data_validation($order->billing_postcode)); $lu->setField("BILL_CITY", $this->payu_data_validation($order->billing_city)); $lu->setField("BILL_STATE", $this->payu_data_validation($order->billing_state)); $lu->setField("BILL_COUNTRYCODE", $this->payu_data_validation($order->billing_country)); // szállítási adatok $lu->setField("DELIVERY_FNAME", $this->payu_data_validation($order->shipping_first_name)); $lu->setField("DELIVERY_LNAME", $this->payu_data_validation($order->shipping_last_name)); $lu->setField("DELIVERY_EMAIL", $order->billing_email); $lu->setField("DELIVERY_PHONE", $this->payu_data_validation($order->billing_phone)); $lu->setField("DELIVERY_ADDRESS", $this->payu_data_validation($order->shipping_address_1)); $lu->setField("DELIVERY_ADDRESS2", $order->shipping_address_2); $lu->setField("DELIVERY_ZIPCODE", $this->payu_data_validation($order->shipping_postcode)); $lu->setField("DELIVERY_CITY", $this->payu_data_validation($order->shipping_city)); $lu->setField("DELIVERY_STATE", $this->payu_data_validation($order->shipping_state)); $lu->setField("DELIVERY_COUNTRYCODE", $this->payu_data_validation($order->shipping_country)); // termékek meghatározása foreach ($order->get_items() as $product) { $lu->addProduct(array('name' => $this->payu_str_replace($product['name']), 'group' => 1, 'code' => $this->payu_set_product_code($product), 'info' => '-', 'price' => round(($product['line_subtotal'] + $product['line_subtotal_tax']) / $product['qty'], 2), 'qty' => $product['qty'], 'vat' => 0)); } $display = $lu->createHtmlForm('payu_payment_form', 'button', __('Please click the button below to pay with PayU', 'wc-payu')); return $display; }
/** * Build discount line item * * @param WC_Order $order * * @return WC_XR_Line_Item */ public function build_discount($order) { if ($order->get_total_discount() > 0) { // Settings object $settings = new WC_XR_Settings(); // Create Line Item object $line_item = new WC_XR_Line_Item(); // Shipping Description $line_item->set_description('Order Discount'); // Shipping Quantity $line_item->set_quantity(1); // Shipping account code $line_item->set_account_code($settings->get_option('discount_account')); // Shipping cost $line_item->set_unit_amount(-$order->get_total_discount()); return $line_item; } }
function order_data($post_id) { global $wpdb; $WooCommerceNFe_Format = new WooCommerceNFe_Format(); $order = new WC_Order($post_id); $coupons = $order->get_used_coupons(); $coupons_percentage = array(); $total_discount = 0; $data = array(); if ($coupons) { foreach ($coupons as $coupon_code) { $coupon_obj = new WC_Coupon($coupon_code); if ($coupon_obj->discount_type == 'percent') { $coupons_percentage[] = $coupon_obj->coupon_amount; } } } if ($order->get_fees()) { foreach ($order->get_fees() as $key => $item) { if ($item['line_total'] < 0) { $discount = $item['line_total'] * -1; $total_discount = $discount + $total_discount; } else { $codigo_ean = get_option('wc_settings_woocommercenfe_ean'); $codigo_ncm = get_option('wc_settings_woocommercenfe_ncm'); $codigo_cest = get_option('wc_settings_woocommercenfe_cest'); $origem = get_option('wc_settings_woocommercenfe_origem'); $imposto = get_option('wc_settings_woocommercenfe_imposto'); $data['produtos'][] = array('nome' => $item['name'], 'sku' => $product->get_sku(), 'ean' => $codigo_ean, 'ncm' => $codigo_ncm, 'cest' => $codigo_cest, 'quantidade' => 1, 'unidade' => 'UN', 'peso' => '0.100', 'origem' => (int) $origem, 'subtotal' => number_format($item['line_subtotal'], 2), 'total' => number_format($item['line_total'], 2), 'classe_imposto' => $imposto); } } } $total_discount = $order->get_total_discount() + $total_discount; // Order $data = array('ID' => $post_id, 'operacao' => 1, 'natureza_operacao' => get_option('wc_settings_woocommercenfe_natureza_operacao'), 'modelo' => 1, 'emissao' => 1, 'finalidade' => 1, 'ambiente' => (int) get_option('wc_settings_woocommercenfe_ambiente')); $data['pedido'] = array('pagamento' => 0, 'presenca' => 2, 'modalidade_frete' => 0, 'frete' => get_post_meta($order->id, '_order_shipping', true), 'desconto' => $total_discount, 'total' => $order->order_total); //Informações COmplementares ao Fisco $fiscoinf = get_option('wc_settings_woocommercenfe_fisco_inf'); if (!empty($fiscoinf) && strlen($fiscoinf) <= 2000) { $data['pedido']['informacoes_fisco'] = $fiscoinf; } //Informações Complementares ao Consumidor $consumidorinf = get_option('wc_settings_woocommercenfe_cons_inf'); if (!empty($consumidorinf) && strlen($consumidorinf) <= 2000) { $data['pedido']['informacoes_complementares'] = $consumidorinf; } // Customer $tipo_pessoa = get_post_meta($post_id, '_billing_persontype', true); if (!$tipo_pessoa) { $tipo_pessoa = 1; } if ($tipo_pessoa == 1) { $data['cliente'] = array('cpf' => $WooCommerceNFe_Format->cpf(get_post_meta($post_id, '_billing_cpf', true)), 'nome_completo' => get_post_meta($post_id, '_billing_first_name', true) . ' ' . get_post_meta($post_id, '_billing_last_name', true), 'endereco' => get_post_meta($post_id, '_shipping_address_1', true), 'complemento' => get_post_meta($post_id, '_shipping_address_2', true), 'numero' => get_post_meta($post_id, '_shipping_number', true), 'bairro' => get_post_meta($post_id, '_shipping_neighborhood', true), 'cidade' => get_post_meta($post_id, '_shipping_city', true), 'uf' => get_post_meta($post_id, '_shipping_state', true), 'cep' => $WooCommerceNFe_Format->cep(get_post_meta($post_id, '_shipping_postcode', true)), 'telefone' => get_user_meta($post_id, 'billing_phone', true), 'email' => get_post_meta($post_id, '_billing_email', true)); } if ($tipo_pessoa == 2) { $data['cliente'] = array('cnpj' => $WooCommerceNFe_Format->cnpj(get_post_meta($post_id, '_billing_cnpj', true)), 'razao_social' => get_post_meta($post_id, '_billing_company', true), 'ie' => get_post_meta($post_id, '_billing_ie', true), 'endereco' => get_post_meta($post_id, '_shipping_address_1', true), 'complemento' => get_post_meta($post_id, '_shipping_address_2', true), 'numero' => get_post_meta($post_id, '_shipping_number', true), 'bairro' => get_post_meta($post_id, '_shipping_neighborhood', true), 'cidade' => get_post_meta($post_id, '_shipping_city', true), 'uf' => get_post_meta($post_id, '_shipping_state', true), 'cep' => $WooCommerceNFe_Format->cep(get_post_meta($post_id, '_shipping_postcode', true)), 'telefone' => get_user_meta($post_id, 'billing_phone', true), 'email' => get_post_meta($post_id, '_billing_email', true)); } // Products foreach ($order->get_items() as $key => $item) { $product_id = $item['product_id']; $variation_id = $item['variation_id']; $ignorar_nfe = get_post_meta($product_id, '_nfe_ignorar_nfe', true); if ($ignorar_nfe == 1 || $order->get_item_subtotal($item, false, false) == 0) { $data['pedido']['total'] -= $item['line_subtotal']; if ($coupons_percentage) { foreach ($coupons_percentage as $percentage) { $data['pedido']['total'] += $percentage / 100 * $item['line_subtotal']; $data['pedido']['desconto'] -= $percentage / 100 * $item['line_subtotal']; } } $data['pedido']['total'] = number_format($data['pedido']['total'], 2); $data['pedido']['desconto'] = number_format($data['pedido']['desconto'], 2); continue; } $emitir = apply_filters('emitir_nfe_produto', true, $product_id); if ($variation_id) { $emitir = apply_filters('emitir_nfe_produto', true, $variation_id); } if ($emitir) { $product = $order->get_product_from_item($item); // Vars $codigo_ean = get_post_meta($product_id, '_nfe_codigo_ean', true); $codigo_ncm = get_post_meta($product_id, '_nfe_codigo_ncm', true); $codigo_cest = get_post_meta($product_id, '_nfe_codigo_cest', true); $origem = get_post_meta($product_id, '_nfe_origem', true); $imposto = get_post_meta($product_id, '_nfe_classe_imposto', true); $peso = $product->get_weight(); if (!$peso) { $peso = '0.100'; } if (!$codigo_ean) { $codigo_ean = get_option('wc_settings_woocommercenfe_ean'); } if (!$codigo_ncm) { $codigo_ncm = get_option('wc_settings_woocommercenfe_ncm'); } if (!$codigo_cest) { $codigo_cest = get_option('wc_settings_woocommercenfe_cest'); } if (!is_numeric($origem)) { $origem = get_option('wc_settings_woocommercenfe_origem'); } if (!$imposto) { $imposto = get_option('wc_settings_woocommercenfe_imposto'); } // Attributes $variacoes = ''; foreach (array_keys($item['item_meta']) as $meta) { if (strpos($meta, 'pa_') !== false) { $atributo = $item[$meta]; $nome_atributo = str_replace('pa_', '', $meta); $nome_atributo = $wpdb->get_var("SELECT attribute_label FROM {$wpdb->prefix}woocommerce_attribute_taxonomies WHERE attribute_name = '{$nome_atributo}'"); $valor = strtoupper($item[$meta]); $variacoes .= ' - ' . strtoupper($nome_atributo) . ': ' . $valor; } } $data['produtos'][] = array('nome' => $item['name'] . $variacoes, 'sku' => $product->get_sku(), 'ean' => $codigo_ean, 'ncm' => $codigo_ncm, 'cest' => $codigo_cest, 'quantidade' => $item['qty'], 'unidade' => 'UN', 'peso' => $peso, 'origem' => (int) $origem, 'subtotal' => number_format($order->get_item_subtotal($item, false, false), 2), 'total' => number_format($order->get_line_total($item, false, false), 2), 'classe_imposto' => $imposto); } } return $data; }
/** * 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); }
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; }
/** * Process the payment and return the result **/ function process_payment($order_id) { global $woocommerce; require_once CI_WC_PATH . "/lib/alipay.config.php"; require_once CI_WC_PATH . "/lib/alipay_service.class.php"; $order = new WC_Order($order_id); if (sizeof($order->get_items()) > 0) { foreach ($order->get_items() as $item) { if ($item['qty']) { $item_names[] = $item['name'] . ' x ' . $item['qty']; } } } ////////////////////////////////////// /**************************请求参数**************************/ //必填参数// $out_trade_no = 'CIP' . $order_id; //请与贵网站订单系统中的唯一订单号匹配 $subject = implode(',', $item_names); //订单名称,显示在支付宝收银台里的“商品名称”里,显示在支付宝的交易管理的“商品名称”的列表里。 $body = implode(',', $item_names); //订单描述、订单详细、订单备注,显示在支付宝收银台里的“商品描述”里 $price = number_format($order->get_order_total() - $order->get_total_discount(), 2, '.', ''); //订单总金额,显示在支付宝收银台里的“应付总额”里 $logistics_fee = "0.00"; //物流费用,即运费。 $logistics_type = "EXPRESS"; //物流类型,三个值可选:EXPRESS(快递)、POST(平邮)、EMS(EMS) $logistics_payment = "SELLER_PAY"; //物流支付方式,两个值可选:SELLER_PAY(卖家承担运费)、BUYER_PAY(买家承担运费) $quantity = "1"; //商品数量,建议默认为1,不改变值,把一次交易看成是一次下订单而非购买一件商品。 $receive_name = ""; //收货人姓名,如:张三 $receive_address = ""; //收货人地址,如:XX省XXX市XXX区XXX路XXX小区XXX栋XXX单元XXX号 $receive_zip = ""; //收货人邮编,如:123456 $receive_phone = ""; //收货人电话号码,如:0571-81234567 $receive_mobile = ""; //收货人手机号码,如:13312341234 //网站商品的展示地址,不允许加?id=123这类自定义参数 $show_url = get_bloginfo('url'); /************************************************************/ //构造要请求的参数数组 $parameter = array("service" => "trade_create_by_buyer", "payment_type" => "1", "partner" => trim($aliapy_config['partner']), "_input_charset" => trim(strtolower($aliapy_config['input_charset'])), "seller_email" => trim($aliapy_config['seller_email']), "return_url" => trim($aliapy_config['return_url']), "notify_url" => trim($aliapy_config['notify_url']), "out_trade_no" => $out_trade_no, "subject" => $subject, "body" => $body, "price" => $price, "quantity" => $quantity, "logistics_fee" => $logistics_fee, "logistics_type" => $logistics_type, "logistics_payment" => $logistics_payment, "receive_name" => $receive_name, "receive_address" => $receive_address, "receive_zip" => $receive_zip, "receive_phone" => $receive_phone, "receive_mobile" => $receive_mobile, "show_url" => $show_url); //构造标准双接口 $alipayService = new AlipayService($aliapy_config); $html_text = $alipayService->trade_create_by_buyer($parameter); //param end $output = "\r\n\t\t\t<html>\r\n\t\t <head>\r\n\t\t\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\r\n\t\t <title>正在前往支付宝...</title>\r\n\t\t </head>\r\n\t\t <body><div style='display:none'>{$html_text}</div>'</body></html>"; echo $output; exit; return array('result' => 'success', 'redirect' => $output); }
/** * Tracks a checkout * @return none */ function track_checkout($order_id, $params) { $this->user["wc cart size"] = 0; $this->user["wc cart value"] = 0; if (!is_user_logged_in()) { $this->user['name'] = $params["billing_first_name"] . " " . $params["billing_last_name"]; $this->user['email'] = $params["billing_email"]; $this->woopra->identify($this->user); } else { $this->woopra_detect(); } global $woocommerce; $cart = $woocommerce->cart; $order = new WC_Order($order_id); $new_params = array("cart subtotal" => $cart->subtotal, "cart value" => $order->get_total(), "cart size" => $order->get_item_count(), "payment method" => $params["payment_method"], "shipping method" => $order->get_shipping_method(), "order discount" => $order->get_total_discount(), "order number" => $order->get_order_number()); $this->woopra->track('wc checkout', $new_params, true); }
/** * Process the payment and return the result * * @access public * @param int $order_id * @return array */ public function process_payment($order_id) { global $woocommerce; $this->init_mijireh(); $mj_order = new Mijireh_Order(); $wc_order = new WC_Order($order_id); // add items to order $items = $wc_order->get_items(); foreach ($items as $item) { $product = $wc_order->get_product_from_item($item); $mj_order->add_item($item['name'], $wc_order->get_item_subtotal($item), $item['qty'], $product->get_sku()); } // add billing address to order $billing = new Mijireh_Address(); $billing->first_name = $wc_order->billing_first_name; $billing->last_name = $wc_order->billing_last_name; $billing->street = $wc_order->billing_address_1; $billing->apt_suite = $wc_order->billing_address_2; $billing->city = $wc_order->billing_city; $billing->state_province = $wc_order->billing_state; $billing->zip_code = $wc_order->billing_postcode; $billing->country = $wc_order->billing_country; $billing->company = $wc_order->billing_company; $billing->phone = $wc_order->billing_phone; if ($billing->validate()) { $mj_order->set_billing_address($billing); } // add shipping address to order $shipping = new Mijireh_Address(); $shipping->first_name = $wc_order->shipping_first_name; $shipping->last_name = $wc_order->shipping_last_name; $shipping->street = $wc_order->shipping_address_1; $shipping->apt_suite = $wc_order->shipping_address_2; $shipping->city = $wc_order->shipping_city; $shipping->state_province = $wc_order->shipping_state; $shipping->zip_code = $wc_order->shipping_postcode; $shipping->country = $wc_order->shipping_country; $shipping->company = $wc_order->shipping_company; if ($shipping->validate()) { $mj_order->set_shipping_address($shipping); } // set order name $mj_order->first_name = $wc_order->billing_first_name; $mj_order->last_name = $wc_order->billing_last_name; $mj_order->email = $wc_order->billing_email; // set order totals $mj_order->total = $wc_order->get_order_total(); $mj_order->tax = $wc_order->get_total_tax(); $mj_order->discount = $wc_order->get_total_discount(); $mj_order->shipping = $wc_order->get_shipping(); // add meta data to identify woocommerce order $mj_order->add_meta_data('wc_order_id', $order_id); // Set URL for mijireh payment notificatoin - use WC API $mj_order->return_url = str_replace('https:', 'http:', add_query_arg('wc-api', 'WC_Mijireh_Checkout', home_url('/'))); // Identify woocommerce $mj_order->partner_id = 'woo'; try { $mj_order->create(); $result = array('result' => 'success', 'redirect' => $mj_order->checkout_url); return $result; } catch (Mijireh_Exception $e) { $woocommerce->add_error(__('Mijireh error:', 'woocommerce') . $e->getMessage()); } }
function get_order_item_totals1( $tax_display = '' ) { if(is_wc_endpoint_url( 'order-received' )) { $order_id=wc_get_order_id_by_order_key( $_GET['key']); $order=new WC_Order($order_id); /*echo '<pre>'; print_r($order); echo '</pre>';*/ $coupons=$order->get_used_coupons(); $coupon_code=$coupons[0]; $coupon_data=new WC_Coupon($coupon_code); $discount = get_post_meta($coupon_data->id,'coupon_amount',true); $type = get_post_meta($coupon_data->id,'discount_type',true); if($type=='percent'){ $coupon_label=$discount.'% Rabatt'; } else{ $coupon_label='Rabatt'; } if ( ! $tax_display ) { $tax_display = $order->tax_display_cart; } if ( 'itemized' == get_option( 'woocommerce_tax_total_display' ) ) { foreach ( $order->get_tax_totals() as $code => $tax ) { $tax->rate = WC_Tax::get_rate_percent( $tax->rate_id ); if ( ! isset( $tax_array[ 'tax_rate'] ) ) $tax_array[ 'tax_rate' ] = array( 'tax' => $tax, 'amount' => $tax->amount, 'contains' => array( $tax ) ); else { array_push( $tax_array[ 'tax_rate' ][ 'contains' ], $tax ); $tax_array[ 'tax_rate' ][ 'amount' ] += $tax->amount; } } if(isset($tax_array['tax_rate']['tax']->rate)) $tax_label='<span class="include_tax">(inkl. '.$tax_array['tax_rate']['tax']->rate.' '.$tax_array['tax_rate']['tax']->label.')</span>'; } $total_rows = array(); $shippingcost='0 '.get_woocommerce_currency_symbol(); if ( $order->get_total_discount() > 0 ) { $total_rows['discount'] = array( 'label' => __( $coupon_label, 'woocommerce' ), 'value' => '-' . $order->get_discount_to_display( $tax_display ) ); } $total_rows['shipping'] = array( 'label' => __( 'Versandkosten', 'woocommerce' ), 'value' =>$shippingcost ); $total_rows['order_total'] = array( 'label' => __( 'Gesamtsumme '.$tax_label, 'woocommerce' ), 'value' => $order->get_formatted_order_total( $tax_display ) ); return $total_rows; } }