payment_complete() 공개 메소드

Most of the time this should mark an order as 'processing' so that admin can process/post the items. If the cart contains only downloadable items then the order is 'completed' since the admin needs to take no action. Stock levels are reduced at this point. Sales are also recorded for products. Finally, record the date of payment. Order must exist.
public payment_complete ( string $transaction_id = '' ) : boolean
$transaction_id string Optional transaction id to store in post meta.
리턴 boolean success
 public function process_payment($order_id)
 {
     global $woocommerce;
     $me = wp_get_current_user();
     $order = new WC_Order($order_id);
     if ($me->ID == 0) {
         $woocommerce->add_error(__('Payment error:', 'woothemes') . __('You must be logged in to use this payment method', 'wc_account_funds'));
         return;
     }
     $funds = get_user_meta($me->ID, 'account_funds', true);
     if (!$funds) {
         $funds = 0;
     }
     if ($funds < $order->order_total) {
         $woocommerce->add_error(__('Payment error:', 'woothemes') . __('Insufficient account balance', 'wc_account_funds'));
         return;
     }
     // Payment complete
     $order->payment_complete();
     // deduct amount from account funds
     $new_funds = $funds - $order->order_total;
     update_user_meta($me->ID, 'account_funds', $new_funds);
     // Remove cart
     $woocommerce->cart->empty_cart();
     // Return thank you page redirect
     if (method_exists($order, 'get_checkout_order_received_url')) {
         return array('result' => 'success', 'redirect' => $order->get_checkout_order_received_url());
     } else {
         return array('result' => 'success', 'redirect' => add_query_arg('key', $order->order_key, add_query_arg('order', $order_id, get_permalink(get_option('woocommerce_thanks_page_id')))));
     }
 }
예제 #2
0
 public function check_ipn_response()
 {
     if (sizeOf($_POST) == 0) {
         header("HTTP/1.1 500 EMPTY_POST ");
         return false;
     }
     if (!isset($_POST['transaction_id']) || !isset($_POST['reference_id'])) {
         header("HTTP/1.1 500 BAD_PARAMETERS");
         return false;
     }
     $transaction_id = filter_var($_POST['transaction_id'], FILTER_SANITIZE_STRING);
     $url = 'https://www.bitpagos.net/api/v1/transaction/' . $transaction_id . '/?api_key=' . $this->get_option('api_key') . '&format=json';
     $cbp = curl_init($url);
     curl_setopt($cbp, CURLOPT_RETURNTRANSFER, TRUE);
     $response_curl = curl_exec($cbp);
     curl_close($cbp);
     $response = json_decode($response_curl);
     $order_id = (int) $_POST['reference_id'];
     if ($order_id != $response->reference_id) {
         die('Wrong reference id');
     }
     if ($response->status == 'PA' || $response->status == 'CO') {
         global $woocommerce;
         $order = new WC_Order($order_id);
         $order->update_status('completed');
         $order->payment_complete();
         file_put_contents('/tmp/ipn.log', print_r($order, TRUE));
         header("HTTP/1.1 200 OK");
     }
 }
 /**
  * Complete a WooCommerce order
  */
 public function completeOrder(WC_Order $order, $payment_hash)
 {
     $status = PayPro_WC_Plugin::$settings->paymentCompleteStatus();
     if (empty($status)) {
         $status = 'wc-processing';
     }
     $order->update_status($status, sprintf(__('PayPro payment succeeded (%s)', 'paypro-gateways-woocommerce'), $payment_hash));
     $order->reduce_order_stock();
     $order->payment_complete();
     $this->removeOrderPaymentHashes($order->id);
 }
 public function check_ipn_response()
 {
     $sha1_hash = $_POST['sha1_hash'];
     $string = array($_POST['notification_type'], $_POST['operation_id'], $_POST['amount'], $_POST['currency'], $_POST['datetime'], $_POST['sender'], $_POST['codepro'], $this->notification_secret, $_POST['label']);
     $sha1_string = sha1(implode('&', $string));
     if ($sha1_hash == $sha1_string) {
         $order = new WC_Order($_POST['label']);
         $order->payment_complete();
         exit;
     } else {
         wp_die();
     }
 }
 public function webhook_handler()
 {
     header('HTTP/1.1 200 OK');
     $obj = file_get_contents('php://input');
     $json = json_decode($obj);
     if ($json->type == 'charge.succeeded') {
         $order_id = $json->transaction->order_id;
         $payment_date = date("Y-m-d", $json->event_date);
         $order = new WC_Order($order_id);
         update_post_meta($order->id, 'openpay_payment_date', $payment_date);
         $order->payment_complete();
         $order->add_order_note(sprintf("Payment completed."));
     }
 }
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     // update pos_cash data
     $tendered = isset($_POST['pos-cash-tendered']) ? wc_format_decimal($_POST['pos-cash-tendered']) : 0;
     $change = isset($_POST['pos-cash-change']) ? wc_format_decimal($_POST['pos-cash-change']) : 0;
     update_post_meta($order_id, '_pos_cash_amount_tendered', $tendered);
     update_post_meta($order_id, '_pos_cash_change', $change);
     // payment complete
     $order->payment_complete();
     // Return thankyou redirect
     return array('result' => 'success');
 }
 /**
  * Updates the status of the order.
  * Webhook needs to be added to Conekta account tusitio.com/wc-api/WC_Conekta_Cash_Gateway
  */
 public function webhook_handler()
 {
     header('HTTP/1.1 200 OK');
     $body = @file_get_contents('php://input');
     $event = json_decode($body);
     $charge = $event->data->object;
     $order_id = $charge->reference_id;
     $paid_at = date("Y-m-d", $charge->paid_at);
     $order = new WC_Order($order_id);
     if (strpos($event->type, "charge.paid") !== false) {
         update_post_meta($order->id, 'conekta-paid-at', $paid_at);
         $order->payment_complete();
         $order->add_order_note(sprintf("Payment completed in Oxxo and notification of payment received"));
     }
 }
 /**
  * mijireh_notification function.
  *
  * @access public
  * @return void
  */
 public function mijireh_notification()
 {
     global $woocommerce;
     $this->init_mijireh();
     try {
         $mj_order = new Mijireh_Order(esc_attr($_GET['order_number']));
         $wc_order_id = $mj_order->get_meta_value('wc_order_id');
         $wc_order = new WC_Order(absint($wc_order_id));
         // Mark order complete
         $wc_order->payment_complete();
         // Empty cart and clear session
         $woocommerce->cart->empty_cart();
         wp_redirect($this->get_return_url($wc_order));
         exit;
     } catch (Mijireh_Exception $e) {
         $woocommerce->add_error(__('Mijireh error:', 'woocommerce') . $e->getMessage());
     }
 }
 public function confirm_url_callback()
 {
     $transaction_id = $_GET['transactionId'];
     $results = get_posts(array('post_type' => 'shop_order', 'meta_query' => array(array('key' => '_hpd_linepay_transactionId', 'value' => $transaction_id))));
     if (!$results) {
         http_response_code(404);
         exit;
     }
     $order_data = $results[0];
     $order_id = $order_data->ID;
     $order = new WC_Order($order_id);
     $response_data = $this->client->confirm($transaction_id, $order->get_total(), get_woocommerce_currency());
     if ($response_data->returnCode != '0000') {
         $order->update_status('failed', sprintf(__('Error return code: %1$s, message: %2$s', 'wc-payment-gateway-line-pay'), $response_data->returnCode, $response_data->returnMessage));
     } else {
         $order->payment_complete();
     }
     wp_redirect($order->get_checkout_order_received_url());
     exit;
 }
예제 #10
0
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     $tendered = isset($_REQUEST['pos-cash-tendered']) ? wc_format_decimal($_REQUEST['pos-cash-tendered']) : 0;
     $tendered = abs((double) $tendered);
     $total = isset($_REQUEST['total']) ? $_REQUEST['total'] : 0;
     $total = abs((double) $total);
     if ($tendered !== 0) {
         // calculate change
         $change = $tendered - $total;
         // add order meta
         update_post_meta($order_id, '_pos_cash_amount_tendered', $tendered);
         update_post_meta($order_id, '_pos_cash_change', $change);
     }
     // payment complete
     $order->payment_complete();
     // Return thankyou redirect
     return array('result' => 'success');
 }
 function check_spectrocoin_callback()
 {
     global $woocommerce;
     $ipn = $_REQUEST;
     // Exit now if the $_POST was empty.
     if (empty($ipn)) {
         echo 'Invalid request!';
         return;
     }
     $scMerchantClient = new SCMerchantClient(SC_API_URL, $this->get_option('merchant_id'), $this->get_option('project_id'), $this->get_option('private_key'));
     $callback = $scMerchantClient->parseCreateOrderCallback($ipn);
     if ($callback != null && $scMerchantClient->validateCreateOrderCallback($callback)) {
         switch ($callback->getStatus()) {
             case OrderStatusEnum::$New:
             case OrderStatusEnum::$Pending:
                 break;
             case OrderStatusEnum::$Expired:
             case OrderStatusEnum::$Failed:
                 break;
             case OrderStatusEnum::$Test:
             case OrderStatusEnum::$Paid:
                 $order_number = (int) $ipn['invoice_id'];
                 $order = new WC_Order(absint($order_number));
                 $order->add_order_note(__('Callback payment completed', 'woocomerce'));
                 $order->payment_complete();
                 $order->reduce_order_stock();
                 break;
             default:
                 echo 'Unknown order status: ' . $callback->getStatus();
                 break;
         }
         $woocommerce->cart->empty_cart();
         echo '*ok*';
     } else {
         echo 'Invalid callback!';
     }
     exit;
 }
 /**
  * Notification callback.
  *
  * @param void
  * @return void
  */
 public function coinsimple_callback()
 {
     // obtain body
     @ob_clean();
     $body = file_get_contents('php://input');
     $data = json_decode($body);
     $business = new \CoinSimple\Business($this->get_option("business_id"), $this->get_option('api_key'));
     if (!$business->validateHash($data->hash, $data->timestamp)) {
         $this->debug(__METHOD__, 'invalid callback hash');
         return;
     }
     $order = new WC_Order($data->custom->order_id);
     if (!isset($order->id)) {
         // orderId invalid, try alternate find
         $orderId = wc_get_order_id_by_order_key($data->custom->order_key);
         $order = new WC_Order($orderId);
     }
     if ($order->order_key !== $data->custom->order_key) {
         $this->debug(__METHOD__, 'invalid order key');
         return;
     }
     $order->payment_complete();
 }
 /**
  * mijireh_notification function.
  *
  * @access public
  * @return void
  */
 public function mijireh_notification()
 {
     if (isset($_GET['order_number'])) {
         $this->init_mijireh();
         try {
             $mj_order = new Mijireh_Order(esc_attr($_GET['order_number']));
             $wc_order_id = $mj_order->get_meta_value('wc_order_id');
             $wc_order = new WC_Order(absint($wc_order_id));
             // Mark order complete
             $wc_order->payment_complete();
             // Empty cart and clear session
             WC()->cart->empty_cart();
             wp_redirect($this->get_return_url($wc_order));
             exit;
         } catch (Mijireh_Exception $e) {
             wc_add_notice(__('Mijireh error:', 'woocommerce') . $e->getMessage(), 'error');
         }
     } elseif (isset($_POST['page_id'])) {
         if (isset($_POST['access_key']) && $_POST['access_key'] == $this->access_key) {
             wp_update_post(array('ID' => $_POST['page_id'], 'post_status' => 'private'));
         }
     }
 }
 public function process_payment($order_id)
 {
     global $woocommerce;
     $customer_order = new WC_Order($order_id);
     $environment = $this->environment == "yes" ? 'TRUE' : 'FALSE';
     $environment_url = "FALSE" == $environment ? 'https://secure.authorize.net/gateway/transact.dll' : 'https://test.authorize.net/gateway/transact.dll';
     $payload = array("x_tran_key" => $this->trans_key, "x_login" => $this->api_login, "x_version" => "3.1", "x_amount" => $customer_order->order_total, "x_card_num" => str_replace(array(' ', '-'), '', $_POST['GP_authorize_gateway-card-number']), "x_card_code" => isset($_POST['GP_authorize_gateway-card-cvc']) ? $_POST['GP_authorize_gateway-card-cvc'] : '', "x_exp_date" => str_replace(array('/', ' '), '', $_POST['GP_authorize_gateway-card-expiry']), "x_type" => 'AUTH_CAPTURE', "x_invoice_num" => str_replace("#", "", $customer_order->get_order_number()), "x_test_request" => $environment, "x_delim_char" => '|', "x_encap_char" => '', "x_delim_data" => "TRUE", "x_relay_response" => "FALSE", "x_method" => "CC", "x_first_name" => $customer_order->billing_first_name, "x_last_name" => $customer_order->billing_last_name, "x_address" => $customer_order->billing_address_1, "x_city" => $customer_order->billing_city, "x_state" => $customer_order->billing_state, "x_zip" => $customer_order->billing_postcode, "x_country" => $customer_order->billing_country, "x_phone" => $customer_order->billing_phone, "x_email" => $customer_order->billing_email, "x_ship_to_first_name" => $customer_order->shipping_first_name, "x_ship_to_last_name" => $customer_order->shipping_last_name, "x_ship_to_company" => $customer_order->shipping_company, "x_ship_to_address" => $customer_order->shipping_address_1, "x_ship_to_city" => $customer_order->shipping_city, "x_ship_to_country" => $customer_order->shipping_country, "x_ship_to_state" => $customer_order->shipping_state, "x_ship_to_zip" => $customer_order->shipping_postcode, "x_cust_id" => $customer_order->user_id, "x_customer_ip" => $_SERVER['REMOTE_ADDR']);
     $response = wp_remote_post($environment_url, array('method' => 'POST', 'body' => http_build_query($payload), 'timeout' => 90, 'sslverify' => false));
     if (is_wp_error($response)) {
         do_action('gp_order_online_completed_failed', $response);
     }
     if (empty($response['body'])) {
         do_action('gp_order_online_completed_failed', $response);
     }
     $response_body = wp_remote_retrieve_body($response);
     // Parse the response into something we can read
     foreach (preg_split("/\r?\n/", $response_body) as $line) {
         $resp = explode("|", $line);
     }
     // Get the values we need
     $r['response_code'] = $resp[0];
     $r['response_sub_code'] = $resp[1];
     $r['response_reason_code'] = $resp[2];
     $r['response_reason_text'] = $resp[3];
     if ($r['response_code'] == 1 || $r['response_code'] == 4) {
         $customer_order->add_order_note(__('Authorize.net payment completed.', 'GP_authorize_gateway'));
         if ($this->mark_order == 'yes') {
             $woocommerce->cart->empty_cart();
             $customer_order->payment_complete();
             $customer_order->update_status('completed');
         }
         do_action('gp_order_online_completed_successfully', $response);
         return array('result' => 'success', 'redirect' => $this->get_return_url($customer_order));
     } else {
         do_action('gp_error_occurred', $r['response_reason_text']);
     }
 }
예제 #15
0
 /**
  * Process the payment
  */
 function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $card_type = isset($_POST['eway_card_type']) ? woocommerce_clean($_POST['eway_card_type']) : '';
     $card_number = isset($_POST['eway_card_number']) ? woocommerce_clean($_POST['eway_card_number']) : '';
     $cardholder_name = isset($_POST['eway_card_holdername']) ? woocommerce_clean($_POST['eway_card_holdername']) : '';
     $card_csc = isset($_POST['eway_card_csc']) ? woocommerce_clean($_POST['eway_card_csc']) : '';
     $card_exp_month = isset($_POST['eway_card_expiration_month']) ? woocommerce_clean($_POST['eway_card_expiration_month']) : '';
     $card_exp_year = isset($_POST['eway_card_expiration_year']) ? woocommerce_clean($_POST['eway_card_expiration_year']) : '';
     // Format card expiration data
     $card_exp_month = (int) $card_exp_month;
     if ($card_exp_month < 10) {
         $card_exp_month = '0' . $card_exp_month;
     }
     $card_exp_year = (int) $card_exp_year;
     $card_exp_year += 2000;
     $card_exp = $card_exp_month . $card_exp_year;
     // Format card number
     $card_number = str_replace(array(' ', '-'), '', $card_number);
     // Send request to eway
     try {
         $url = $this->antifraud == "yes" ? $this->antifraudurl : $this->testmode == 'yes' ? $this->testurl : $this->liveurl;
         $post_data = array('ewayCustomerID' => $this->customer_id, 'ewayTotalAmount' => $order->order_total * 100, 'ewayCardNumber' => $card_number, 'ewayCardExpiryMonth' => $card_exp_month, 'ewayCardExpiryYear' => $card_exp_year, 'ewayCVN' => $card_csc, 'ewayTrxnNumber' => '', 'ewayCustomerInvoiceDescription' => '', 'ewayCustomerInvoiceRef' => '', 'ewayOption1' => '', 'ewayOption2' => '', 'ewayOption3' => '', 'ewayCustomerFirstName' => $order->billing_first_name, 'ewayCustomerLastName' => $order->billing_last_name, 'ewayCustomerEmail' => $order->billing_email, 'ewayCardHoldersName' => $cardholder_name, 'ewayCustomerAddress' => $order->billing_address_1 . ' ' . $order->billing_address_2 . ' ' . $order->billing_city . ' ' . $order->billing_state . ' ' . $order->billing_country, 'ewayCustomerPostcode' => $order->billing_postcode);
         if ($this->antifraud == "yes") {
             $post_data['ewayCustomerIPAddress'] = $this->get_user_ip();
             $post_data['ewayCustomerBillingCountry'] = $this->get_country_code();
         }
         $xmlRequest = "<ewaygateway>";
         foreach ($post_data as $key => $value) {
             $xmlRequest .= "<{$key}>{$value}</{$key}>";
         }
         $xmlRequest .= "</ewaygateway>";
         $response = wp_remote_post($url, array('method' => 'POST', 'body' => $xmlRequest, 'timeout' => 70, 'sslverify' => true));
         if (is_wp_error($response)) {
             throw new Exception(__('There was a problem connecting to the payment gateway.', 'woothemes'));
         }
         if (empty($response['body'])) {
             throw new Exception(__('Empty eWAY response.', 'woothemes'));
         }
         $parsed_response = $response['body'];
         $parsed_response = $this->parseResponse($parsed_response);
         switch (strtolower($parsed_response['EWAYTRXNSTATUS'])) {
             case 'true':
                 // Add order note
                 $order->add_order_note(sprintf(__('eWAY payment completed', 'woothemes')));
                 // Payment complete
                 $order->payment_complete();
                 // Remove cart
                 $woocommerce->cart->empty_cart();
                 // Empty awaiting payment session
                 unset($_SESSION['order_awaiting_payment']);
                 // Return thank you page redirect
                 return array('result' => 'success', 'redirect' => add_query_arg('key', $order->order_key, add_query_arg('order', $order_id, get_permalink(get_option('woocommerce_thanks_page_id')))));
                 break;
             case 'false':
                 // Payment failed :(
                 $order->add_order_note(sprintf(__('eWAY payment failed (Correlation ID: %s). Payment was rejected due to an error: ', 'woothemes'), $parsed_response['EWAYAUTHCODE']) . '"' . $parsed_response['EWAYTRXNERROR'] . '"');
                 $woocommerce->add_error(__('Payment error:', 'woothemes') . $parsed_response['EWAYTRXNERROR']);
                 return;
                 break;
             default:
                 // Payment failed :(
                 $order->add_order_note(sprintf(__('eWAY payment failed (Correlation ID: %s). Payment was rejected due to an error: ', 'woothemes'), $parsed_response['CORRELATIONID']) . '"' . $error_message . '"');
                 $woocommerce->add_error(__('Payment error:', 'woothemes') . $parsed_response['EWAYTRXNERROR']);
                 return;
                 break;
         }
     } catch (Exception $e) {
         $woocommerce->add_error(__('Connection error:', 'woothemes') . ': "' . $e->getMessage() . '"');
         return;
     }
 }
예제 #16
0
 /**
  * Process the payment and return the result
  *
  * @access public
  * @param int $order_id
  * @return array
  */
 function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $token = $_POST['payfortToken'];
     try {
         if (empty($token)) {
             $error_msg = __('Please make sure your card details have been entered correctly.', 'woocommerce');
             throw new Start_Error($error_msg);
         }
         $charge_description = $order->id . ": WooCommerce charge for " . $order->billing_email;
         $order_items = $order->get_items();
         $order_items_array_full = array();
         $user_info = wp_get_current_user();
         $user_name = $user_info->user_login;
         $udata = get_userdata($user_info->ID);
         if (isset($udata->user_registered)) {
             $registered_at = date(DATE_ISO8601, strtotime($udata->user_registered));
         } else {
             $registered_at = date(DATE_ISO8601, strtotime(date("Y-m-d H:i:s")));
         }
         foreach ($order_items as $key => $items) {
             $itemClass = new WC_Product($items['product_id']);
             $order_items_array['title'] = $items['name'];
             $order_items_array['amount'] = round($itemClass->get_price(), 2) * $this->currency_multiplier[get_woocommerce_currency()];
             $order_items_array['quantity'] = $items['qty'];
             array_push($order_items_array_full, $order_items_array);
         }
         $billing_address = array("first_name" => $order->billing_first_name, "last_name" => $order->billing_last_name, "country" => $order->billing_country, "city" => $order->billing_city, "address_1" => $order->billing_address_1, "address_2" => $order->billing_address_2, "phone" => $order->billing_phone, "postcode" => $order->billing_postcode);
         $shipping_address = array("first_name" => $order->shipping_first_name, "last_name" => $order->shipping_last_name, "country" => $order->shipping_country, "city" => $order->shipping_city, "address_1" => $order->shipping_address_1, "address_2" => $order->shipping_address_2, "phone" => $order->shipping_phone, "postcode" => $order->shipping_postcode);
         $shopping_cart_array = array('user_name' => $user_name, 'registered_at' => $registered_at, 'items' => $order_items_array_full, 'billing_address' => $billing_address, 'shipping_address' => $shipping_address);
         $charge_args = array('description' => $charge_description, 'card' => $token, 'currency' => strtoupper(get_woocommerce_currency()), 'email' => $order->billing_email, 'ip' => $_SERVER['REMOTE_ADDR'], 'amount' => $order->get_total() * $this->currency_multiplier[get_woocommerce_currency()], 'shopping_cart' => $shopping_cart_array, 'shipping_amount' => round($order->get_total_shipping(), 2) * $this->currency_multiplier[get_woocommerce_currency()], 'metadata' => array('reference_id' => $order_id));
         if ($this->test_mode == 'yes') {
             Start::setApiKey($this->test_secret_key);
         } else {
             Start::setApiKey($this->live_secret_key);
         }
         $start_plugin_data = get_file_data('wp-content/plugins/payfort/woocommerce-payfort.php', array('Version'), 'plugin');
         $woo_plugin_data = get_file_data('wp-content/plugins/woocommerce/woocommerce.php', array('Version'), 'plugin');
         $userAgent = 'WooCommerce ' . $woo_plugin_data['0'] . ' / Start Plugin ' . $start_plugin_data['0'];
         Start::setUserAgent($userAgent);
         $charge = Start_Charge::create($charge_args);
         // No exceptions? Yaay, all done!
         $order->payment_complete();
         return array('result' => 'success', 'redirect' => $this->get_return_url($order));
     } catch (Start_Error $e) {
         // TODO: Can we get the extra params (so the error is more apparent)?
         // e.g. Instead of "request params are invalid", we get
         // "extras":{"amount":["minimum amount (in the smallest currency unit) is 185 for AED"]
         $error_code = $e->getErrorCode();
         if ($error_code === "card_declined") {
             $message = __('Error: ', 'woothemes') . $e->getMessage() . " Please, try with another card";
         } else {
             $message = __('Error: ', 'woothemes') . $e->getMessage();
         }
         // If function should we use?
         if (function_exists("wc_add_notice")) {
             // Use the new version of the add_error method
             wc_add_notice($message, 'error');
         } else {
             // Use the old version
             $woocommerce->add_error($message);
         }
         // we raise 'update_checkout' event for javscript
         // to remove card token
         WC()->session->set('refresh_totals', true);
         return array('result' => 'fail', 'redirect' => '');
     }
 }
예제 #17
0
 /**
  * Process the checkout after the confirm order button is pressed
  *
  * @access public
  * @return void
  */
 public function process_checkout()
 {
     global $wpdb, $woocommerce, $current_user;
     $woocommerce->verify_nonce('process_checkout');
     if (!defined('WOOCOMMERCE_CHECKOUT')) {
         define('WOOCOMMERCE_CHECKOUT', true);
     }
     // Prevent timeout
     @set_time_limit(0);
     do_action('woocommerce_before_checkout_process');
     if (sizeof($woocommerce->cart->get_cart()) == 0) {
         $woocommerce->add_error(sprintf(__('Sorry, your session has expired. <a href="%s">Return to homepage &rarr;</a>', 'woocommerce'), home_url()));
     }
     do_action('woocommerce_checkout_process');
     // Checkout fields (not defined in checkout_fields)
     $this->posted['shiptobilling'] = isset($_POST['shiptobilling']) ? 1 : 0;
     $this->posted['terms'] = isset($_POST['terms']) ? 1 : 0;
     $this->posted['createaccount'] = isset($_POST['createaccount']) ? 1 : 0;
     $this->posted['payment_method'] = isset($_POST['payment_method']) ? woocommerce_clean($_POST['payment_method']) : '';
     $this->posted['shipping_method'] = isset($_POST['shipping_method']) ? woocommerce_clean($_POST['shipping_method']) : '';
     // Ship to billing only option
     if ($woocommerce->cart->ship_to_billing_address_only()) {
         $this->posted['shiptobilling'] = 1;
     }
     // Update customer shipping and payment method to posted method
     $woocommerce->session->chosen_shipping_method = $this->posted['shipping_method'];
     $woocommerce->session->chosen_payment_method = $this->posted['payment_method'];
     // Note if we skip shipping
     $skipped_shipping = false;
     // Get validation class
     $validation = $woocommerce->validation();
     // Get posted checkout_fields and do validation
     foreach ($this->checkout_fields as $fieldset_key => $fieldset) {
         // Skip shipping if its not needed
         if ($fieldset_key == 'shipping' && ($woocommerce->cart->ship_to_billing_address_only() || $this->posted['shiptobilling'] || !$woocommerce->cart->needs_shipping() && get_option('woocommerce_require_shipping_address') == 'no')) {
             $skipped_shipping = true;
             continue;
         }
         foreach ($fieldset as $key => $field) {
             if (!isset($field['type'])) {
                 $field['type'] = 'text';
             }
             // Get Value
             switch ($field['type']) {
                 case "checkbox":
                     $this->posted[$key] = isset($_POST[$key]) ? 1 : 0;
                     break;
                 case "multiselect":
                     $this->posted[$key] = isset($_POST[$key]) ? implode(', ', array_map('woocommerce_clean', $_POST[$key])) : '';
                     break;
                 default:
                     $this->posted[$key] = isset($_POST[$key]) ? woocommerce_clean($_POST[$key]) : '';
                     break;
             }
             // Hooks to allow modification of value
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_' . sanitize_title($field['type']) . '_field', $this->posted[$key]);
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_field_' . $key, $this->posted[$key]);
             // Validation: Required fields
             if (isset($field['required']) && $field['required'] && empty($this->posted[$key])) {
                 $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is a required field.', 'woocommerce'));
             }
             if (!empty($this->posted[$key])) {
                 // Special handling for validation and formatting
                 switch ($key) {
                     case "billing_postcode":
                     case "shipping_postcode":
                         $validate_against = $key == 'billing_postcode' ? 'billing_country' : 'shipping_country';
                         $this->posted[$key] = strtoupper(str_replace(' ', '', $this->posted[$key]));
                         if (!$validation->is_postcode($this->posted[$key], $_POST[$validate_against])) {
                             $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . sprintf(__('(%s) is not a valid postcode/ZIP.', 'woocommerce'), $this->posted[$key]));
                         } else {
                             $this->posted[$key] = $validation->format_postcode($this->posted[$key], $_POST[$validate_against]);
                         }
                         break;
                     case "billing_state":
                     case "shipping_state":
                         // Get valid states
                         $validate_against = $key == 'billing_state' ? 'billing_country' : 'shipping_country';
                         $valid_states = $woocommerce->countries->get_states($_POST[$validate_against]);
                         if ($valid_states) {
                             $valid_state_values = array_flip(array_map('strtolower', $valid_states));
                         }
                         // Convert value to key if set
                         if (isset($valid_state_values[strtolower($this->posted[$key])])) {
                             $this->posted[$key] = $valid_state_values[strtolower($this->posted[$key])];
                         }
                         // Only validate if the country has specific state options
                         if ($valid_states && sizeof($valid_states) > 0) {
                             if (!in_array($this->posted[$key], array_keys($valid_states))) {
                                 $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is not valid. Please enter one of the following:', 'woocommerce') . ' ' . implode(', ', $valid_states));
                             }
                         }
                         break;
                     case "billing_phone":
                         $this->posted[$key] = $validation->format_phone($this->posted[$key]);
                         if (!$validation->is_phone($this->posted[$key])) {
                             $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is not a valid number.', 'woocommerce'));
                         }
                         break;
                     case "billing_email":
                         $this->posted[$key] = strtolower($this->posted[$key]);
                         if (!$validation->is_email($this->posted[$key])) {
                             $woocommerce->add_error('<strong>' . $field['label'] . '</strong> ' . __('is not a valid email address.', 'woocommerce'));
                         }
                         break;
                 }
             }
         }
     }
     // Update customer location to posted location so we can correctly check available shipping methods
     if (isset($this->posted['billing_country'])) {
         $woocommerce->customer->set_country($this->posted['billing_country']);
     }
     if (isset($this->posted['billing_state'])) {
         $woocommerce->customer->set_state($this->posted['billing_state']);
     }
     if (isset($this->posted['billing_postcode'])) {
         $woocommerce->customer->set_postcode($this->posted['billing_postcode']);
     }
     // Shipping Information
     if (!$skipped_shipping) {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['shipping_country'])) {
             $woocommerce->customer->set_shipping_country($this->posted['shipping_country']);
         }
         if (isset($this->posted['shipping_state'])) {
             $woocommerce->customer->set_shipping_state($this->posted['shipping_state']);
         }
         if (isset($this->posted['shipping_postcode'])) {
             $woocommerce->customer->set_shipping_postcode($this->posted['shipping_postcode']);
         }
     } else {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['billing_country'])) {
             $woocommerce->customer->set_shipping_country($this->posted['billing_country']);
         }
         if (isset($this->posted['billing_state'])) {
             $woocommerce->customer->set_shipping_state($this->posted['billing_state']);
         }
         if (isset($this->posted['billing_postcode'])) {
             $woocommerce->customer->set_shipping_postcode($this->posted['billing_postcode']);
         }
     }
     // Update cart totals now we have customer address
     $woocommerce->cart->calculate_totals();
     // Handle accounts
     if (is_user_logged_in()) {
         $this->creating_account = false;
     } elseif (!empty($this->posted['createaccount'])) {
         $this->creating_account = true;
     } elseif ($this->must_create_account) {
         $this->creating_account = true;
     } else {
         $this->creating_account = false;
     }
     if ($this->creating_account) {
         if (get_option('woocommerce_registration_email_for_username') == 'no') {
             if (empty($this->posted['account_username'])) {
                 $woocommerce->add_error(__('Please enter an account username.', 'woocommerce'));
             }
             // Check the username
             if (!validate_username($this->posted['account_username'])) {
                 $woocommerce->add_error(__('Invalid email/username.', 'woocommerce'));
             } elseif (username_exists($this->posted['account_username'])) {
                 $woocommerce->add_error(__('An account is already registered with that username. Please choose another.', 'woocommerce'));
             }
         } else {
             $this->posted['account_username'] = $this->posted['billing_email'];
         }
         // Validate passwords
         if (empty($this->posted['account_password'])) {
             $woocommerce->add_error(__('Please enter an account password.', 'woocommerce'));
         }
         if ($this->posted['account_password-2'] !== $this->posted['account_password']) {
             $woocommerce->add_error(__('Passwords do not match.', 'woocommerce'));
         }
         // Check the e-mail address
         if (email_exists($this->posted['billing_email'])) {
             $woocommerce->add_error(__('An account is already registered with your email address. Please login.', 'woocommerce'));
         }
     }
     // Terms
     if (!isset($_POST['woocommerce_checkout_update_totals']) && empty($this->posted['terms']) && woocommerce_get_page_id('terms') > 0) {
         $woocommerce->add_error(__('You must accept our Terms &amp; Conditions.', 'woocommerce'));
     }
     if ($woocommerce->cart->needs_shipping()) {
         // Shipping Method
         $available_methods = $woocommerce->shipping->get_available_shipping_methods();
         if (!isset($available_methods[$this->posted['shipping_method']])) {
             $this->shipping_method = '';
             $woocommerce->add_error(__('Invalid shipping method.', 'woocommerce'));
         } else {
             $this->shipping_method = $available_methods[$this->posted['shipping_method']];
         }
     }
     if ($woocommerce->cart->needs_payment()) {
         // Payment Method
         $available_gateways = $woocommerce->payment_gateways->get_available_payment_gateways();
         if (!isset($available_gateways[$this->posted['payment_method']])) {
             $this->payment_method = '';
             $woocommerce->add_error(__('Invalid payment method.', 'woocommerce'));
         } else {
             $this->payment_method = $available_gateways[$this->posted['payment_method']];
             $this->payment_method->validate_fields();
         }
     }
     // Action after validation
     do_action('woocommerce_after_checkout_validation', $this->posted);
     if (!isset($_POST['woocommerce_checkout_update_totals']) && $woocommerce->error_count() == 0) {
         $this->customer_id = get_current_user_id();
         try {
             // Create customer account and log them in
             if ($this->creating_account && !$this->customer_id) {
                 $reg_errors = new WP_Error();
                 do_action('woocommerce_register_post', $this->posted['account_username'], $this->posted['billing_email'], $reg_errors);
                 $errors = apply_filters('woocommerce_registration_errors', $reg_errors, $this->posted['account_username'], $this->posted['billing_email']);
                 // if there are no errors, let's create the user account
                 if (!$reg_errors->get_error_code()) {
                     $user_pass = esc_attr($this->posted['account_password']);
                     $new_customer_data = array('user_login' => $this->posted['account_username'], 'user_pass' => $user_pass, 'user_email' => $this->posted['billing_email'], 'role' => 'customer');
                     $this->customer_id = wp_insert_user(apply_filters('woocommerce_new_customer_data', $new_customer_data));
                     if (is_wp_error($this->customer_id)) {
                         throw new MyException('<strong>' . __('ERROR', 'woocommerce') . '</strong>: ' . __('Couldn&#8217;t register you&hellip; please contact us if you continue to have problems.', 'woocommerce'));
                     }
                     // Set the global user object
                     $current_user = get_user_by('id', $this->customer_id);
                     // Action
                     do_action('woocommerce_created_customer', $this->customer_id);
                     // send the user a confirmation and their login details
                     $mailer = $woocommerce->mailer();
                     $mailer->customer_new_account($this->customer_id, $user_pass);
                     // set the WP login cookie
                     $secure_cookie = is_ssl() ? true : false;
                     wp_set_auth_cookie($this->customer_id, true, $secure_cookie);
                 } else {
                     throw new MyException($reg_errors->get_error_message());
                 }
             }
             // Abort if errors are present
             if ($woocommerce->error_count() > 0) {
                 throw new MyException();
             }
             // Create the order
             $order_id = $this->create_order();
             // Order is saved
             do_action('woocommerce_checkout_order_processed', $order_id, $this->posted);
             // Process payment
             if ($woocommerce->cart->needs_payment()) {
                 // Store Order ID in session so it can be re-used after payment failure
                 $woocommerce->session->order_awaiting_payment = $order_id;
                 // Process Payment
                 $result = $available_gateways[$this->posted['payment_method']]->process_payment($order_id);
                 // Redirect to success/confirmation/payment page
                 if ($result['result'] == 'success') {
                     $result = apply_filters('woocommerce_payment_successful_result', $result);
                     if (is_ajax()) {
                         echo '<!--WC_START-->' . json_encode($result) . '<!--WC_END-->';
                         exit;
                     } else {
                         wp_redirect($result['redirect']);
                         exit;
                     }
                 }
             } else {
                 if (empty($order)) {
                     $order = new WC_Order($order_id);
                 }
                 // No payment was required for order
                 $order->payment_complete();
                 // Empty the Cart
                 $woocommerce->cart->empty_cart();
                 // Get redirect
                 $return_url = get_permalink(woocommerce_get_page_id('thanks'));
                 $return_url = add_query_arg('key', $order->order_key, add_query_arg('order', $order->id, $return_url));
                 // Redirect to success/confirmation/payment page
                 if (is_ajax()) {
                     echo '<!--WC_START-->' . json_encode(array('result' => 'success', 'redirect' => apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order))) . '<!--WC_END-->';
                     exit;
                 } else {
                     wp_safe_redirect(apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order));
                     exit;
                 }
             }
         } catch (Exception $e) {
             if (!empty($e)) {
                 $woocommerce->add_error($e);
             }
         }
     }
     // endif
     // If we reached this point then there were errors
     if (is_ajax()) {
         ob_start();
         $woocommerce->show_messages();
         $messages = ob_get_clean();
         echo '<!--WC_START-->' . json_encode(array('result' => 'failure', 'messages' => $messages, 'refresh' => isset($woocommerce->session->refresh_totals) ? 'true' : 'false')) . '<!--WC_END-->';
         unset($woocommerce->session->refresh_totals);
         exit;
     }
 }
/**
 * Process the pay form.
 *
 * @access public
 * @return void
 */
function woocommerce_pay_action()
{
    global $woocommerce;
    if (isset($_POST['woocommerce_pay']) && $woocommerce->verify_nonce('pay')) {
        ob_start();
        // Pay for existing order
        $order_key = urldecode($_GET['order']);
        $order_id = absint($_GET['order_id']);
        $order = new WC_Order($order_id);
        if ($order->id == $order_id && $order->order_key == $order_key && in_array($order->status, array('pending', 'failed'))) {
            // Set customer location to order location
            if ($order->billing_country) {
                $woocommerce->customer->set_country($order->billing_country);
            }
            if ($order->billing_state) {
                $woocommerce->customer->set_state($order->billing_state);
            }
            if ($order->billing_postcode) {
                $woocommerce->customer->set_postcode($order->billing_postcode);
            }
            if ($order->billing_city) {
                $woocommerce->customer->set_city($order->billing_city);
            }
            // Update payment method
            if ($order->order_total > 0) {
                $payment_method = woocommerce_clean($_POST['payment_method']);
                $available_gateways = $woocommerce->payment_gateways->get_available_payment_gateways();
                // Update meta
                update_post_meta($order_id, '_payment_method', $payment_method);
                if (isset($available_gateways[$payment_method])) {
                    $payment_method_title = $available_gateways[$payment_method]->get_title();
                }
                update_post_meta($order_id, '_payment_method_title', $payment_method_title);
                // Validate
                $available_gateways[$payment_method]->validate_fields();
                // Process
                if ($woocommerce->error_count() == 0) {
                    $result = $available_gateways[$payment_method]->process_payment($order_id);
                    // Redirect to success/confirmation/payment page
                    if ($result['result'] == 'success') {
                        wp_redirect($result['redirect']);
                        exit;
                    }
                }
            } else {
                // No payment was required for order
                $order->payment_complete();
                wp_safe_redirect(get_permalink(woocommerce_get_page_id('thanks')));
                exit;
            }
        }
    }
}
 /**
  * Process the order status.
  *
  * @param  WC_Order $order
  * @param  string   $payment_id
  * @param  string   $status
  * @param  string   $auth_code
  *
  * @return bool
  */
 public function process_order_status($order, $payment_id, $status, $auth_code)
 {
     if ('APPROVED' == $status) {
         // Payment complete
         $order->payment_complete($payment_id);
         // Add order note
         $order->add_order_note(sprintf(__('Simplify payment approved (ID: %1$s, Auth Code: %2$s)', 'woocommerce'), $payment_id, $auth_code));
         // Remove cart
         WC()->cart->empty_cart();
         return true;
     }
     return false;
 }
 /**
  * Update order status.
  *
  * @param array $posted PagSeguro post data.
  */
 public function update_order_status($posted)
 {
     if (isset($posted->reference)) {
         $order_id = (int) str_replace($this->invoice_prefix, '', $posted->reference);
         $order = new WC_Order($order_id);
         // Checks whether the invoice number matches the order.
         // If true processes the payment.
         if ($order->id === $order_id) {
             if ('yes' == $this->debug) {
                 $this->log->add($this->id, 'PagSeguro payment status for order ' . $order->get_order_number() . ' is: ' . intval($posted->status));
             }
             // Order details.
             $order_details = array('type' => '', 'method' => '', 'installments' => '', 'link' => '');
             if (isset($posted->code)) {
                 update_post_meta($order->id, __('PagSeguro Transaction ID', 'woocommerce-pagseguro'), (string) $posted->code);
             }
             if (isset($posted->sender->email)) {
                 update_post_meta($order->id, __('Payer email', 'woocommerce-pagseguro'), (string) $posted->sender->email);
             }
             if (isset($posted->sender->name)) {
                 update_post_meta($order->id, __('Payer name', 'woocommerce-pagseguro'), (string) $posted->sender->name);
             }
             if (isset($posted->paymentMethod->type)) {
                 $order_details['type'] = intval($posted->paymentMethod->type);
                 update_post_meta($order->id, __('Payment type', 'woocommerce-pagseguro'), $this->api->get_payment_name_by_type($order_details['type']));
             }
             if (isset($posted->paymentMethod->code)) {
                 $order_details['method'] = $this->api->get_payment_method_name(intval($posted->paymentMethod->code));
                 update_post_meta($order->id, __('Payment method', 'woocommerce-pagseguro'), $order_details['method']);
             }
             if (isset($posted->installmentCount)) {
                 $order_details['installments'] = (string) $posted->installmentCount;
                 update_post_meta($order->id, __('Installments', 'woocommerce-pagseguro'), $order_details['installments']);
             }
             if (isset($posted->paymentLink)) {
                 $order_details['link'] = (string) $posted->paymentLink;
                 update_post_meta($order->id, __('Payment url', 'woocommerce-pagseguro'), $order_details['link']);
             }
             // Save/update payment information for transparente checkout.
             if ('transparent' == $this->method) {
                 update_post_meta($order->id, '_wc_pagseguro_payment_data', $order_details);
             }
             switch (intval($posted->status)) {
                 case 1:
                     $order->update_status('on-hold', __('PagSeguro: The buyer initiated the transaction, but so far the PagSeguro not received any payment information.', 'woocommerce-pagseguro'));
                     break;
                 case 2:
                     $order->update_status('on-hold', __('PagSeguro: Payment under review.', 'woocommerce-pagseguro'));
                     break;
                 case 3:
                     $order->add_order_note(__('PagSeguro: Payment approved.', 'woocommerce-pagseguro'));
                     // For WooCommerce 2.2 or later.
                     add_post_meta($order->id, '_transaction_id', (string) $posted->code, true);
                     // Changing the order for processing and reduces the stock.
                     $order->payment_complete();
                     break;
                 case 4:
                     $order->add_order_note(__('PagSeguro: Payment completed and credited to your account.', 'woocommerce-pagseguro'));
                     break;
                 case 5:
                     $order->update_status('on-hold', __('PagSeguro: Payment came into dispute.', 'woocommerce-pagseguro'));
                     $this->send_email(sprintf(__('Payment for order %s came into dispute', 'woocommerce-pagseguro'), $order->get_order_number()), __('Payment in dispute', 'woocommerce-pagseguro'), sprintf(__('Order %s has been marked as on-hold, because the payment came into dispute in PagSeguro.', 'woocommerce-pagseguro'), $order->get_order_number()));
                     break;
                 case 6:
                     $order->update_status('refunded', __('PagSeguro: Payment refunded.', 'woocommerce-pagseguro'));
                     $this->send_email(sprintf(__('Payment for order %s refunded', 'woocommerce-pagseguro'), $order->get_order_number()), __('Payment refunded', 'woocommerce-pagseguro'), sprintf(__('Order %s has been marked as refunded by PagSeguro.', 'woocommerce-pagseguro'), $order->get_order_number()));
                     break;
                 case 7:
                     $order->update_status('cancelled', __('PagSeguro: Payment canceled.', 'woocommerce-pagseguro'));
                     break;
                 default:
                     // No action xD.
                     break;
             }
         } else {
             if ('yes' == $this->debug) {
                 $this->log->add($this->id, 'Error: Order Key does not match with PagSeguro reference.');
             }
         }
     }
 }
 public function executepay()
 {
     if (empty(WC()->session->token) || empty(WC()->session->PayerID) || empty(WC()->session->paymentId)) {
         return;
     }
     $execution = new PaymentExecution();
     $execution->setPayerId(WC()->session->PayerID);
     try {
         $payment = Payment::get(WC()->session->paymentId, $this->getAuth());
         $payment->execute($execution, $this->getAuth());
         $this->add_log(print_r($payment, true));
         if ($payment->state == "approved") {
             //if state = approved continue..
             global $wpdb;
             $this->log->add('paypal_plus', sprintf(__('Response: %s', 'paypal-for-woocommerce'), print_r($payment, true)));
             $order = new WC_Order(WC()->session->orderId);
             if ($this->billing_address == 'yes') {
                 require_once "lib/NameParser.php";
                 $parser = new FullNameParser();
                 $split_name = $parser->split_full_name($payment->payer->payer_info->shipping_address->recipient_name);
                 $shipping_first_name = $split_name['fname'];
                 $shipping_last_name = $split_name['lname'];
                 $full_name = $split_name['fullname'];
                 update_post_meta(WC()->session->orderId, '_billing_first_name', $shipping_first_name);
                 update_post_meta(WC()->session->orderId, '_billing_last_name', $shipping_last_name);
                 update_post_meta(WC()->session->orderId, '_billing_full_name', $full_name);
                 update_post_meta(WC()->session->orderId, '_billing_address_1', $payment->payer->payer_info->shipping_address->line1);
                 update_post_meta(WC()->session->orderId, '_billing_address_2', $payment->payer->payer_info->shipping_address->line2);
                 update_post_meta(WC()->session->orderId, '_billing_city', $payment->payer->payer_info->shipping_address->city);
                 update_post_meta(WC()->session->orderId, '_billing_postcode', $payment->payer->payer_info->shipping_address->postal_code);
                 update_post_meta(WC()->session->orderId, '_billing_country', $payment->payer->payer_info->shipping_address->country_code);
                 update_post_meta(WC()->session->orderId, '_billing_state', $payment->payer->payer_info->shipping_address->state);
             }
             $order->add_order_note(__('PayPal Plus payment completed', 'paypal-for-woocommerce'));
             $order->payment_complete($payment->id);
             //add hook
             do_action('woocommerce_checkout_order_processed', WC()->session->orderId);
             wp_redirect($this->get_return_url($order));
         }
     } catch (PayPal\Exception\PayPalConnectionException $ex) {
         wc_add_notice(__("Error processing checkout. Please try again. ", 'woocommerce'), 'error');
         $this->add_log($ex->getData());
     } catch (Exception $ex) {
         $this->add_log($ex->getMessage());
         // Prints the Error Code
         wc_add_notice(__("Error processing checkout. Please try again.", 'woocommerce'), 'error');
     }
 }
예제 #22
0
function paymill_webhooks()
{
    global $wpdb;
    // is there a webhook from Paymill?
    if (class_exists('WC_Subscriptions_Manager')) {
        // grab data from webhook
        $body = @file_get_contents('php://input');
        $event_json = json_decode($body, true);
        // retrieve sub ID
        if (isset($event_json['event']['event_resource']['id']) && strlen($event_json['event']['event_resource']['id']) > 0) {
            $paymill_sub_id = $event_json['event']['event_resource']['id'];
        } elseif (isset($event_json['event']['event_resource']['subscription']['id']) && strlen($event_json['event']['event_resource']['subscription']['id']) > 0) {
            $paymill_sub_id = $event_json['event']['event_resource']['subscription']['id'];
        }
        error_log("\n\n########################################################################################################################\n\n", 3, PAYMILL_DIR . 'lib/debug/PHP_errors.log');
        error_log(date(DATE_RFC822) . ' - Webhook ' . $event_json['event']['event_type'] . ' (Resource-ID: ' . $paymill_sub_id . ') triggered - start processing' . "\n\n", 3, PAYMILL_DIR . 'lib/debug/PHP_errors.log');
        /* output example:
        				array(1) {
        				  ["event"]=>
        				  array(4) {
        					["event_type"]=>
        					string(20) "subscription.deleted"
        					["event_resource"]=>
        					array(13) {
        					  ["id"]=>
        					  string(24) "sub_b71adbf5....."
        					  ["offer"]=>
        					  array(10) {
        						["id"]=>
        						string(26) "offer_8083a5b....."
        						["name"]=>
        						string(39) "woo_91_73da6....."
        						["amount"]=>
        						int(100)
        						["currency"]=>
        						string(3) "EUR"
        						["interval"]=>
        						string(5) "1 DAY"
        						["trial_period_days"]=>
        						int(0)
        						["created_at"]=>
        						int(1389547028)
        						["updated_at"]=>
        						int(1389547028)
        						["subscription_count"]=>
        						array(2) {
        						  ["active"]=>
        						  string(1) "1"
        						  ["inactive"]=>
        						  string(1) "1"
        						}
        						["app_id"]=>
        						NULL
        					  }
        					  ["livemode"]=>
        					  bool(false)
        					  ["cancel_at_period_end"]=>
        					  bool(false)
        					  ["trial_start"]=>
        					  NULL
        					  ["trial_end"]=>
        					  NULL
        					  ["next_capture_at"]=>
        					  int(1389836717)
        					  ["created_at"]=>
        					  int(1389663382)
        					  ["updated_at"]=>
        					  int(1389750317)
        					  ["canceled_at"]=>
        					  NULL
        					  ["app_id"]=>
        					  NULL
        					  ["payment"]=>
        					  array(12) {
        						["id"]=>
        						string(28) "pay_4e3759f....."
        						["type"]=>
        						string(10) "creditcard"
        						["client"]=>
        						string(27) "client_dbe164....."
        						["card_type"]=>
        						string(4) "visa"
        						["country"]=>
        						NULL
        						["expire_month"]=>
        						string(2) "12"
        						["expire_year"]=>
        						string(4) "2020"
        						["card_holder"]=>
        						string(13) "dfgdfgdfgdfgd"
        						["last4"]=>
        						string(4) "1111"
        						["created_at"]=>
        						int(1389663369)
        						["updated_at"]=>
        						int(1389663380)
        						["app_id"]=>
        						NULL
        					  }
        					  ["client"]=>
        					  array(8) {
        						["id"]=>
        						string(27) "client_dbe164....."
        						["email"]=>
        						string(22) "*****@*****.**"
        						["description"]=>
        						string(15) "Matthias Reuter"
        						["created_at"]=>
        						int(1389547027)
        						["updated_at"]=>
        						int(1389547027)
        						["app_id"]=>
        						NULL
        						["payment"]=>
        						array(2) {
        						  [0]=>
        						  array(12) {
        							["id"]=>
        							string(28) "pay_1a5ff8....."
        							["type"]=>
        							string(10) "creditcard"
        							["client"]=>
        							string(27) "client_dbe16....."
        							["card_type"]=>
        							string(4) "visa"
        							["country"]=>
        							NULL
        							["expire_month"]=>
        							string(2) "12"
        							["expire_year"]=>
        							string(4) "2020"
        							["card_holder"]=>
        							string(10) "dfgdfgdfgd"
        							["last4"]=>
        							string(4) "1111"
        							["created_at"]=>
        							int(1389547027)
        							["updated_at"]=>
        							int(1389547028)
        							["app_id"]=>
        							NULL
        						  }
        						  [1]=>
        						  array(12) {
        							["id"]=>
        							string(28) "pay_4e375....."
        							["type"]=>
        							string(10) "creditcard"
        							["client"]=>
        							string(27) "client_dbe164....."
        							["card_type"]=>
        							string(4) "visa"
        							["country"]=>
        							NULL
        							["expire_month"]=>
        							string(2) "12"
        							["expire_year"]=>
        							string(4) "2020"
        							["card_holder"]=>
        							string(13) "dfgdfgdfgdfgd"
        							["last4"]=>
        							string(4) "1111"
        							["created_at"]=>
        							int(1389663369)
        							["updated_at"]=>
        							int(1389663380)
        							["app_id"]=>
        							NULL
        						  }
        						}
        						["subscription"]=>
        						array(2) {
        						  [0]=>
        						  string(24) "sub_fcc4....."
        						  [1]=>
        						  string(24) "sub_b71a....."
        						}
        					  }
        					}
        					["created_at"]=>
        					int(1389816435)
        					["app_id"]=>
        					NULL
        				  }
        				}
        				
        			*/
        //error_log(var_export($event_json,true)."\n\n", 3, PAYMILL_DIR.'lib/debug/PHP_errors.log');
        // get subscription info, if available
        if (isset($paymill_sub_id) && strlen($paymill_sub_id) > 0) {
            $sql = $wpdb->prepare('SELECT * FROM ' . $wpdb->prefix . 'paymill_subscriptions WHERE paymill_sub_id=%s', array($paymill_sub_id));
            $sub_cache = $wpdb->get_results($sql, ARRAY_A);
            $sub_cache = $sub_cache[0];
            /* output example:
            			SELECT * FROM wp_paymill_subscriptions WHERE paymill_sub_id="sub_b71adbf5e097bbe5ba80"
            			*/
            error_log("\n\n" . $sql . "\n\n", 3, PAYMILL_DIR . 'lib/debug/PHP_errors.log');
            /* output example:
            			
            			1
            			
            			30
            			
            			*/
            //error_log($sub_cache['woo_user_id']."\n\n".$sub_cache['woo_offer_id']."\n\n", 3, PAYMILL_DIR.'lib/debug/PHP_errors.log');
            $subscription = WC_Subscriptions_Manager::get_subscription($sub_cache['woo_offer_id']);
            // update subscriptions when webhook is triggered
            if (isset($sub_cache['woo_offer_id']) && strlen($sub_cache['woo_offer_id']) > 0) {
                // subscription successfully created
                if ($event_json['event']['event_type'] == 'subscription.created') {
                }
                // tell WooCommerce when payment for subscription is successfully processed
                if ($event_json['event']['event_type'] == 'subscription.succeeded') {
                    /* example data WC_Subscriptions_Manager::get_subscription:
                    				array(15) {
                    				  ["order_id"]=>
                    				  string(3) "201"
                    				  ["product_id"]=>
                    				  string(2) "91"
                    				  ["variation_id"]=>
                    				  string(0) ""
                    				  ["status"]=>
                    				  string(6) "active"
                    				  ["period"]=>
                    				  string(3) "day"
                    				  ["interval"]=>
                    				  string(1) "1"
                    				  ["length"]=>
                    				  string(2) "12"
                    				  ["start_date"]=>
                    				  string(19) "2014-01-12 17:17:10"
                    				  ["expiry_date"]=>
                    				  string(19) "2014-01-24 17:17:10"
                    				  ["end_date"]=>
                    				  string(1) "0"
                    				  ["trial_expiry_date"]=>
                    				  string(1) "0"
                    				  ["failed_payments"]=>
                    				  string(1) "0"
                    				  ["completed_payments"]=>
                    				  array(1) {
                    					[0]=>
                    					string(19) "2014-01-12 17:17:10"
                    				  }
                    				  ["suspension_count"]=>
                    				  string(1) "0"
                    				  ["last_payment_date"]=>
                    				  string(19) "2014-01-12 17:17:10"
                    				}
                    			*/
                    error_log(var_export($subscription, true) . "\n\n", 3, PAYMILL_DIR . 'lib/debug/PHP_errors.log');
                    // prevent multiple subscription renewals because of multiple webhook attempts.
                    $whole_period = 0;
                    switch ($subscription['period']) {
                        case 'day':
                        default:
                            $whole_period = intval($subscription['interval']) * 86400;
                            break;
                        case 'week':
                            $whole_period = intval($subscription['interval']) * 604800;
                            break;
                        case 'month':
                            $whole_period = intval($subscription['interval']) * 2160000;
                            // using 25 days to prevent problems with shorter months
                            break;
                        case 'year':
                            $whole_period = intval($subscription['interval']) * 30240000;
                            // using 350 days to prevent any timezone problems whatsoever
                            break;
                    }
                    if (count($subscription['completed_payments']) >= 1) {
                        if (strtotime(date(DATE_RFC822)) > strtotime($subscription['last_payment_date']) + $whole_period - 18000) {
                            // minus 5 hours to prevent any problems with pending triggers
                            $order = new WC_Order($subscription['order_id']);
                            //WC_Subscriptions_Manager::process_subscription_payments_on_order($order, $subscription['product_id']);
                            WC_Subscriptions_Manager::process_subscription_payments_on_order($order);
                        }
                    } else {
                        $order = new WC_Order($subscription['order_id']);
                        $order->payment_complete();
                        WC_Subscriptions_Manager::activate_subscriptions_for_order($subscription['order_id']);
                    }
                    WC_Subscriptions_Manager::set_next_payment_date($sub_cache['woo_offer_id'], $order->customer_user);
                }
                // cancel subscription, as it was deleted through Paymill dashboard
                if ($event_json['event']['event_type'] == 'subscription.deleted') {
                    $sql = $wpdb->prepare('DELETE FROM ' . $wpdb->prefix . 'paymill_subscriptions WHERE woo_user_id=%s AND woo_offer_id=%s', array($sub_cache['woo_user_id'], $sub_cache['woo_offer_id']));
                    $wpdb->query($sql);
                    error_log("\n\n" . $sql . "\n\n", 3, PAYMILL_DIR . 'lib/debug/PHP_errors.log');
                    //WC_Subscriptions_Manager::cancel_subscriptions_for_order( $order );
                    WC_Subscriptions_Manager::cancel_subscription($sub_cache['woo_user_id'], $sub_cache['woo_offer_id']);
                }
                // tell WC that payment failure occured
                if ($event_json['event']['event_type'] == 'subscription.failed') {
                    WC_Subscriptions_Manager::process_subscription_payment_failure_on_order($subscription['order_id'], $subscription['product_id']);
                }
            }
        }
        error_log(date(DATE_RFC822) . ' - Webhook ' . $event_json['event']['event_type'] . ' finished - end processing' . "\n\n", 3, PAYMILL_DIR . 'lib/debug/PHP_errors.log');
        error_log("\n\n########################################################################################################################\n\n", 3, PAYMILL_DIR . 'lib/debug/PHP_errors.log');
    }
}
	/**
	* process the payment and return the result
	* @param int $order_id
	* @return array
	*/
	public function process_payment($order_id) {
		global $woocommerce;

		$order = new WC_Order($order_id);
		$ccfields = $this->getCardFields();

		$isLiveSite = ($this->eway_sandbox != 'yes');

		if ($this->eway_stored == 'yes')
			$eway = new EwayPaymentsStoredPayment($this->eway_customerid, $isLiveSite);
		else
			$eway = new EwayPaymentsPayment($this->eway_customerid, $isLiveSite);

		$eway->invoiceDescription		= get_bloginfo('name');
		$eway->invoiceReference			= $order->get_order_number();						// customer invoice reference
		$eway->transactionNumber		= $order_id;										// transaction reference
		$eway->cardHoldersName			= $ccfields['eway_card_name'];
		$eway->cardNumber				= strtr($ccfields['eway_card_number'], array(' ' => '', '-' => ''));
		$eway->cardExpiryMonth			= $ccfields['eway_expiry_month'];
		$eway->cardExpiryYear			= $ccfields['eway_expiry_year'];
		$eway->cardVerificationNumber	= $ccfields['eway_cvn'];
		$eway->firstName				= $order->billing_first_name;
		$eway->lastName					= $order->billing_last_name;
		$eway->emailAddress				= $order->billing_email;
		$eway->postcode					= $order->billing_postcode;

		// for Beagle (free) security
		if ($this->eway_beagle == 'yes') {
			$eway->customerCountryCode = $order->billing_country;
		}

		// convert WooCommerce country code into country name
		$billing_country = $order->billing_country;
		if (isset($woocommerce->countries->countries[$billing_country])) {
			$billing_country = $woocommerce->countries->countries[$billing_country];
		}

		// aggregate street, city, state, country into a single string
		$parts = array (
			$order->billing_address_1,
			$order->billing_address_2,
			$order->billing_city,
			$order->billing_state,
			$billing_country,
		);
		$eway->address = implode(', ', array_filter($parts, 'strlen'));

		// use cardholder name for last name if no customer name entered
		if (empty($eway->firstName) && empty($eway->lastName)) {
			$eway->lastName				= $eway->cardHoldersName;
		}

		// allow plugins/themes to modify invoice description and reference, and set option fields
		$eway->invoiceDescription		= apply_filters('woocommerce_eway_invoice_desc', $eway->invoiceDescription, $order_id);
		$eway->invoiceReference			= apply_filters('woocommerce_eway_invoice_ref', $eway->invoiceReference, $order_id);
		$eway->option1					= apply_filters('woocommerce_eway_option1', '', $order_id);
		$eway->option2					= apply_filters('woocommerce_eway_option2', '', $order_id);
		$eway->option3					= apply_filters('woocommerce_eway_option3', '', $order_id);

		// if live, pass through amount exactly, but if using test site, round up to whole dollars or eWAY will fail
		$total = $order->order_total;
		$eway->amount					= $isLiveSite ? $total : ceil($total);

		try {
			$response = $eway->processPayment();

			if ($response->status) {
				// transaction was successful, so record details and complete payment
				update_post_meta($order_id, 'Transaction ID', $response->transactionNumber);
				if (!empty($response->authCode)) {
					update_post_meta($order_id, 'Authcode', $response->authCode);
				}
				if (!empty($response->beagleScore)) {
					update_post_meta($order_id, 'Beagle score', $response->beagleScore);
				}

				if ($this->eway_stored == 'yes') {
					// payment hasn't happened yet, so record status as 'on-hold' and reduce stock in anticipation
					$order->reduce_order_stock();
					$order->update_status('on-hold', 'Awaiting stored payment');
					unset($_SESSION['order_awaiting_payment']);
				}
				else {
					$order->payment_complete();
				}
				$woocommerce->cart->empty_cart();

				$result = array(
					'result' => 'success',
					'redirect' => $this->get_return_url($order),
				);
			}
			else {
				// transaction was unsuccessful, so record transaction number and the error
				$order->update_status('failed', nl2br(esc_html($response->error)));
				wc_add_notice(nl2br(esc_html($response->error)), 'error');
				$result = array('result' => 'failure');
			}
		}
		catch (EwayPaymentsException $e) {
			// an exception occured, so record the error
			$order->update_status('failed', nl2br(esc_html($e->getMessage())));
			wc_add_notice(nl2br(esc_html($e->getMessage())), 'error');
			$result = array('result' => 'failure');
		}

		return $result;
	}
 /**
  * Process the subscription
  *
  * Saves the card, if needed, and activates the subscription. This is called when the subscription is first purchased
  *
  * @param int $order_id
  *
  * @return array
  *
  * @since 0.6.0
  */
 public function process_subscription($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $user_id = get_current_user_id();
     $profile_id = $this->profiles_enabled ? $this->saved_cards->get_user_profile_id($user_id) : false;
     $token = isset($_POST['card_connect_token']) ? wc_clean($_POST['card_connect_token']) : false;
     $card_name = isset($_POST['card_connect-card-name']) ? wc_clean($_POST['card_connect-card-name']) : false;
     $store_new_card = isset($_POST['card_connect-save-card']) ? wc_clean($_POST['card_connect-save-card']) : false;
     $saved_card_id = isset($_POST['card_connect-cards']) ? wc_clean($_POST['card_connect-cards']) : false;
     $card_alias = isset($_POST['card_connect-new-card-alias']) ? wc_clean($_POST['card_connect-new-card-alias']) : false;
     if (!$token && !$saved_card_id) {
         wc_add_notice(__('Payment error: ', 'woothemes') . 'Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'error');
         return;
     }
     $request = array('merchid' => $this->api_credentials['mid'], 'cvv2' => wc_clean($_POST['card_connect-card-cvc']), 'amount' => $order->order_total * 100, 'currency' => "USD", 'orderid' => sprintf(__('%s - Order #%s', 'woocommerce'), esc_html(get_bloginfo('name', 'display')), $order->get_order_number()), 'name' => $card_name ? $card_name : trim($order->billing_first_name . ' ' . $order->billing_last_name), 'street' => $order->billing_address_1, 'city' => $order->billing_city, 'region' => $order->billing_state, 'country' => $order->billing_country, 'postal' => $order->billing_postcode, 'capture' => $this->mode === 'capture' ? 'Y' : 'N');
     if ($saved_card_id) {
         // Payment is using a stored card, no token or account number to pass
         $request['profile'] = "{$profile_id}/{$saved_card_id}";
     } else {
         // Either a basic purchase or adding a new card. Either way, include the expiration date
         $request['expiry'] = preg_replace('/[^\\d]/i', '', wc_clean($_POST['card_connect-card-expiry']));
         // Adding an additional card to an existing profile -- This requires a separate API call, handled in `add_account_to_profile`
         if ($profile_id) {
             $request['profile'] = $profile_id;
             // The `token` key isn't used by the Auth/Capture service however it's ignored if it's passed as `account` when updating profiles
             $request['token'] = $token;
             // Get the new card's account id, remove the token key
             $new_account_id = $this->saved_cards->add_account_to_profile($user_id, $card_alias, $request);
             unset($request['token']);
             // Overwrite the profile field with the `profile/acctid` format required by the Auth/Capture service
             $request['profile'] = "{$profile_id}/{$new_account_id}";
             // Adding a new card, no existing profile
         } else {
             $request['profile'] = 'Y';
             $request['account'] = $token;
         }
     }
     //Authorizes transaction to be processed
     if (!is_null($this->get_cc_client())) {
         $response = $this->get_cc_client()->authorizeTransaction($request);
     } else {
         wc_add_notice(__('Payment error: ', 'woothemes') . 'CardConnect is not configured! ', 'error');
         $order->add_order_note('CardConnect is not configured!');
         return;
     }
     // 'A' response is for accepted
     if ('A' === $response['respstat']) {
         // Need to verify customer data before marking complete
         $order_verification = $this->verify_customer_data($response);
         if (!$order_verification['is_valid']) {
             $request = array('merchid' => $this->api_credentials['mid'], 'currency' => 'USD', 'retref' => $response['retref']);
             if (!is_null($this->get_cc_client())) {
                 $void_response = $this->get_cc_client()->voidTransaction($request);
             } else {
                 wc_add_notice(__('Payment error: ', 'woothemes') . 'CardConnect is not configured! ', 'error');
                 $order->add_order_note('CardConnect is not configured!');
                 return;
             }
             if ($void_response['authcode'] === 'REVERS') {
                 $order->update_status('failed', __('Payment Failed', 'cardconnect-payment-gateway'));
                 foreach ($order_verification['errors'] as $error) {
                     $order->add_order_note(sprintf(__($error, 'woocommerce')));
                     wc_add_notice(__('Payment error: ', 'woothemes') . $error, 'error');
                 }
                 return;
             }
         }
         // Mark order complete and begin completion process
         $order->payment_complete($response['retref']);
         update_post_meta($order_id, '_transaction_id', $response['retref']);
         // Reduce stock levels
         $order->reduce_order_stock();
         // Remove cart
         $woocommerce->cart->empty_cart();
         $order->add_order_note(sprintf(__('CardConnect payment approved (ID: %s, Authcode: %s)', 'woocommerce'), $response['retref'], $response['authcode']));
         // First time this customer has saved a card, pull the response fields and store in user meta
         if (!$saved_card_id && !$profile_id) {
             $this->saved_cards->set_user_profile_id($user_id, $response['profileid']);
             $this->saved_cards->save_user_card($user_id, array($response['acctid'] => $card_alias));
         }
         // Activate the subscription
         WC_Subscriptions_Manager::activate_subscriptions_for_order($order);
         // Return thankyou redirect
         return array('result' => 'success', 'redirect' => $this->get_return_url($order));
     } else {
         if ('C' === $response['respstat']) {
             wc_add_notice(__('Payment error: ', 'woothemes') . 'Order Declined : ' . $response['resptext'], 'error');
             $order->add_order_note(sprintf(__('CardConnect declined transaction. Response: %s', 'woocommerce'), $response['resptext']));
         } else {
             wc_add_notice(__('Payment error: ', 'woothemes') . 'An error prevented this transaction from completing. Please confirm your information and try again.', 'error');
             $order->add_order_note(sprintf(__('CardConnect failed transaction. Response: %s', 'woocommerce'), $response['resptext']));
         }
     }
     $order->update_status('failed', __('Payment Failed', 'cardconnect-payment-gateway'));
     return;
 }
 /**
  * Process the checkout after the confirm order button is pressed
  *
  * @access public
  * @return void
  */
 public function process_checkout()
 {
     global $wpdb, $current_user;
     wp_verify_nonce($_POST['_wpnonce'], 'woocommerce-process_checkout');
     if (!defined('WOOCOMMERCE_CHECKOUT')) {
         define('WOOCOMMERCE_CHECKOUT', true);
     }
     // Prevent timeout
     @set_time_limit(0);
     do_action('woocommerce_before_checkout_process');
     if (sizeof(WC()->cart->get_cart()) == 0) {
         wc_add_notice(sprintf(__('Sorry, your session has expired. <a href="%s" class="wc-backward">Return to homepage</a>', 'woocommerce'), home_url()), 'error');
     }
     do_action('woocommerce_checkout_process');
     // Checkout fields (not defined in checkout_fields)
     $this->posted['terms'] = isset($_POST['terms']) ? 1 : 0;
     $this->posted['createaccount'] = isset($_POST['createaccount']) ? 1 : 0;
     $this->posted['payment_method'] = isset($_POST['payment_method']) ? stripslashes($_POST['payment_method']) : '';
     $this->posted['shipping_method'] = isset($_POST['shipping_method']) ? $_POST['shipping_method'] : '';
     $this->posted['ship_to_different_address'] = isset($_POST['ship_to_different_address']) ? true : false;
     if (isset($_POST['shiptobilling'])) {
         _deprecated_argument('WC_Checkout::process_checkout()', '2.1', 'The "shiptobilling" field is deprecated. THe template files are out of date');
         $this->posted['ship_to_different_address'] = $_POST['shiptobilling'] ? false : true;
     }
     // Ship to billing only option
     if (WC()->cart->ship_to_billing_address_only()) {
         $this->posted['ship_to_different_address'] = false;
     }
     // Update customer shipping and payment method to posted method
     $chosen_shipping_methods = WC()->session->get('chosen_shipping_methods');
     if (isset($this->posted['shipping_method']) && is_array($this->posted['shipping_method'])) {
         foreach ($this->posted['shipping_method'] as $i => $value) {
             $chosen_shipping_methods[$i] = wc_clean($value);
         }
     }
     WC()->session->set('chosen_shipping_methods', $chosen_shipping_methods);
     WC()->session->set('chosen_payment_method', $this->posted['payment_method']);
     // Note if we skip shipping
     $skipped_shipping = false;
     // Get posted checkout_fields and do validation
     foreach ($this->checkout_fields as $fieldset_key => $fieldset) {
         // Skip shipping if not needed
         if ($fieldset_key == 'shipping' && ($this->posted['ship_to_different_address'] == false || !WC()->cart->needs_shipping())) {
             $skipped_shipping = true;
             continue;
         }
         // Ship account if not needed
         if ($fieldset_key == 'account' && (is_user_logged_in() || $this->must_create_account == false && empty($this->posted['createaccount']))) {
             continue;
         }
         foreach ($fieldset as $key => $field) {
             if (!isset($field['type'])) {
                 $field['type'] = 'text';
             }
             // Get Value
             switch ($field['type']) {
                 case "checkbox":
                     $this->posted[$key] = isset($_POST[$key]) ? 1 : 0;
                     break;
                 case "multiselect":
                     $this->posted[$key] = isset($_POST[$key]) ? implode(', ', array_map('wc_clean', $_POST[$key])) : '';
                     break;
                 case "textarea":
                     $this->posted[$key] = isset($_POST[$key]) ? wp_strip_all_tags(wp_check_invalid_utf8(stripslashes($_POST[$key]))) : '';
                     break;
                 default:
                     $this->posted[$key] = isset($_POST[$key]) ? wc_clean($_POST[$key]) : '';
                     break;
             }
             // Hooks to allow modification of value
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_' . sanitize_title($field['type']) . '_field', $this->posted[$key]);
             $this->posted[$key] = apply_filters('woocommerce_process_checkout_field_' . $key, $this->posted[$key]);
             // Validation: Required fields
             if (isset($field['required']) && $field['required'] && empty($this->posted[$key])) {
                 wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is a required field.', 'woocommerce'), 'error');
             }
             if (!empty($this->posted[$key])) {
                 // Validation rules
                 if (!empty($field['validate']) && is_array($field['validate'])) {
                     foreach ($field['validate'] as $rule) {
                         switch ($rule) {
                             case 'postcode':
                                 $this->posted[$key] = strtoupper(str_replace(' ', '', $this->posted[$key]));
                                 if (!WC_Validation::is_postcode($this->posted[$key], $_POST[$fieldset_key . '_country'])) {
                                     wc_add_notice(__('Please enter a valid postcode/ZIP.', 'woocommerce'), 'error');
                                 } else {
                                     $this->posted[$key] = wc_format_postcode($this->posted[$key], $_POST[$fieldset_key . '_country']);
                                 }
                                 break;
                             case 'phone':
                                 $this->posted[$key] = wc_format_phone_number($this->posted[$key]);
                                 if (!WC_Validation::is_phone($this->posted[$key])) {
                                     wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not a valid phone number.', 'woocommerce'), 'error');
                                 }
                                 break;
                             case 'email':
                                 $this->posted[$key] = strtolower($this->posted[$key]);
                                 if (!is_email($this->posted[$key])) {
                                     wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not a valid email address.', 'woocommerce'), 'error');
                                 }
                                 break;
                             case 'state':
                                 // Get valid states
                                 $valid_states = WC()->countries->get_states($_POST[$fieldset_key . '_country']);
                                 if ($valid_states) {
                                     $valid_state_values = array_flip(array_map('strtolower', $valid_states));
                                 }
                                 // Convert value to key if set
                                 if (isset($valid_state_values[strtolower($this->posted[$key])])) {
                                     $this->posted[$key] = $valid_state_values[strtolower($this->posted[$key])];
                                 }
                                 // Only validate if the country has specific state options
                                 if ($valid_states && sizeof($valid_states) > 0) {
                                     if (!in_array($this->posted[$key], array_keys($valid_states))) {
                                         wc_add_notice('<strong>' . $field['label'] . '</strong> ' . __('is not valid. Please enter one of the following:', 'woocommerce') . ' ' . implode(', ', $valid_states), 'error');
                                     }
                                 }
                                 break;
                         }
                     }
                 }
             }
         }
     }
     // Update customer location to posted location so we can correctly check available shipping methods
     if (isset($this->posted['billing_country'])) {
         WC()->customer->set_country($this->posted['billing_country']);
     }
     if (isset($this->posted['billing_state'])) {
         WC()->customer->set_state($this->posted['billing_state']);
     }
     if (isset($this->posted['billing_postcode'])) {
         WC()->customer->set_postcode($this->posted['billing_postcode']);
     }
     // Shipping Information
     if (!$skipped_shipping) {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['shipping_country'])) {
             WC()->customer->set_shipping_country($this->posted['shipping_country']);
         }
         if (isset($this->posted['shipping_state'])) {
             WC()->customer->set_shipping_state($this->posted['shipping_state']);
         }
         if (isset($this->posted['shipping_postcode'])) {
             WC()->customer->set_shipping_postcode($this->posted['shipping_postcode']);
         }
     } else {
         // Update customer location to posted location so we can correctly check available shipping methods
         if (isset($this->posted['billing_country'])) {
             WC()->customer->set_shipping_country($this->posted['billing_country']);
         }
         if (isset($this->posted['billing_state'])) {
             WC()->customer->set_shipping_state($this->posted['billing_state']);
         }
         if (isset($this->posted['billing_postcode'])) {
             WC()->customer->set_shipping_postcode($this->posted['billing_postcode']);
         }
     }
     // Update cart totals now we have customer address
     WC()->cart->calculate_totals();
     // Terms
     if (!isset($_POST['woocommerce_checkout_update_totals']) && empty($this->posted['terms']) && wc_get_page_id('terms') > 0) {
         wc_add_notice(__('You must accept our Terms &amp; Conditions.', 'woocommerce'), 'error');
     }
     if (WC()->cart->needs_shipping()) {
         if (!in_array(WC()->customer->get_shipping_country(), array_keys(WC()->countries->get_shipping_countries()))) {
             wc_add_notice(sprintf(__('Unfortunately <strong>we do not ship to %s</strong>. Please enter an alternative shipping address.', 'woocommerce'), WC()->countries->shipping_to_prefix() . ' ' . WC()->customer->get_shipping_country()), 'error');
         }
         // Validate Shipping Methods
         $packages = WC()->shipping->get_packages();
         $this->shipping_methods = WC()->session->get('chosen_shipping_methods');
         foreach ($packages as $i => $package) {
             if (!isset($package['rates'][$this->shipping_methods[$i]])) {
                 wc_add_notice(__('Invalid shipping method.', 'woocommerce'), 'error');
                 $this->shipping_methods[$i] = '';
             }
         }
     }
     if (WC()->cart->needs_payment()) {
         // Payment Method
         $available_gateways = WC()->payment_gateways->get_available_payment_gateways();
         if (!isset($available_gateways[$this->posted['payment_method']])) {
             $this->payment_method = '';
             wc_add_notice(__('Invalid payment method.', 'woocommerce'), 'error');
         } else {
             $this->payment_method = $available_gateways[$this->posted['payment_method']];
             $this->payment_method->validate_fields();
         }
     }
     // Action after validation
     do_action('woocommerce_after_checkout_validation', $this->posted);
     if (!isset($_POST['woocommerce_checkout_update_totals']) && wc_notice_count('error') == 0) {
         try {
             // Customer accounts
             $this->customer_id = apply_filters('woocommerce_checkout_customer_id', get_current_user_id());
             if (!is_user_logged_in() && ($this->must_create_account || !empty($this->posted['createaccount']))) {
                 $username = !empty($this->posted['account_username']) ? $this->posted['account_username'] : '';
                 $password = !empty($this->posted['account_password']) ? $this->posted['account_password'] : '';
                 $new_customer = wc_create_new_customer($this->posted['billing_email'], $username, $password);
                 if (is_wp_error($new_customer)) {
                     throw new Exception($new_customer->get_error_message());
                 }
                 $this->customer_id = $new_customer;
                 wc_set_customer_auth_cookie($this->customer_id);
                 // As we are now logged in, checkout will need to refresh to show logged in data
                 WC()->session->set('reload_checkout', true);
                 // Add customer info from other billing fields
                 if ($this->posted['billing_first_name'] && apply_filters('woocommerce_checkout_update_customer_data', true, $this)) {
                     $userdata = array('ID' => $this->customer_id, 'first_name' => $this->posted['billing_first_name'] ? $this->posted['billing_first_name'] : '', 'last_name' => $this->posted['billing_last_name'] ? $this->posted['billing_last_name'] : '', 'display_name' => $this->posted['billing_first_name'] ? $this->posted['billing_first_name'] : '');
                     wp_update_user(apply_filters('woocommerce_checkout_customer_userdata', $userdata, $this));
                 }
             }
             // Do a final stock check at this point
             $this->check_cart_items();
             // Abort if errors are present
             if (wc_notice_count('error') > 0) {
                 throw new Exception();
             }
             $order_id = $this->create_order();
             do_action('woocommerce_checkout_order_processed', $order_id, $this->posted);
             // Process payment
             if (WC()->cart->needs_payment()) {
                 // Store Order ID in session so it can be re-used after payment failure
                 WC()->session->order_awaiting_payment = $order_id;
                 // Process Payment
                 $result = $available_gateways[$this->posted['payment_method']]->process_payment($order_id);
                 // Redirect to success/confirmation/payment page
                 if ($result['result'] == 'success') {
                     $result = apply_filters('woocommerce_payment_successful_result', $result, $order_id);
                     if (is_ajax()) {
                         echo '<!--WC_START-->' . json_encode($result) . '<!--WC_END-->';
                         exit;
                     } else {
                         wp_redirect($result['redirect']);
                         exit;
                     }
                 }
             } else {
                 if (empty($order)) {
                     $order = new WC_Order($order_id);
                 }
                 // No payment was required for order
                 $order->payment_complete();
                 // Empty the Cart
                 WC()->cart->empty_cart();
                 // Get redirect
                 $return_url = $order->get_checkout_order_received_url();
                 // Redirect to success/confirmation/payment page
                 if (is_ajax()) {
                     echo '<!--WC_START-->' . json_encode(array('result' => 'success', 'redirect' => apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order))) . '<!--WC_END-->';
                     exit;
                 } else {
                     wp_safe_redirect(apply_filters('woocommerce_checkout_no_payment_needed_redirect', $return_url, $order));
                     exit;
                 }
             }
         } catch (Exception $e) {
             if (!empty($e)) {
                 wc_add_notice($e->getMessage(), 'error');
             }
         }
     }
     // endif
     // If we reached this point then there were errors
     if (is_ajax()) {
         ob_start();
         wc_print_notices();
         $messages = ob_get_clean();
         echo '<!--WC_START-->' . json_encode(array('result' => 'failure', 'messages' => $messages, 'refresh' => isset(WC()->session->refresh_totals) ? 'true' : 'false', 'reload' => isset(WC()->session->reload_checkout) ? 'true' : 'false')) . '<!--WC_END-->';
         unset(WC()->session->refresh_totals, WC()->session->reload_checkout);
         exit;
     }
 }
예제 #26
0
 /**
  * Check for 2Checkout Response
  *
  * @access public
  * @return void
  */
 function check_ipn_response()
 {
     global $woocommerce;
     @ob_clean();
     $wc_order_id = $_REQUEST['merchant_order_id'];
     $compare_string = $this->secret_word . $this->seller_id . $_REQUEST['order_number'] . $_REQUEST['total'];
     $compare_hash1 = strtoupper(md5($compare_string));
     $compare_hash2 = $_REQUEST['key'];
     if ($compare_hash1 != $compare_hash2) {
         wp_die("2Checkout Hash Mismatch... check your secret word.");
     } else {
         $wc_order = new WC_Order(absint($wc_order_id));
         // Mark order complete
         $wc_order->payment_complete();
         // Empty cart and clear session
         $woocommerce->cart->empty_cart();
         wp_redirect($this->get_return_url($wc_order));
         exit;
     }
 }
예제 #27
0
 function _requests($_notification)
 {
     global $woocommerce;
     $order = new WC_Order($_notification->order_id);
     if ($_notification->status == 'COMPLETE') {
         $order->payment_complete();
         $woocommerce->cart->empty_cart();
     } elseif ($_notification->status == 'PENDING') {
         $order->update_status('on-hold');
     } elseif ($_notification->status == 'FAIL') {
         $order->update_status('failed');
     }
     exit;
 }
 /**
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     // get order object
     $order = new WC_Order($order_id);
     $cashback = isset($_POST['pos-cashback']) ? wc_format_decimal($_POST['pos-cashback']) : 0;
     if ($cashback !== 0) {
         // add order meta
         update_post_meta($order_id, '_pos_card_cashback', $cashback);
         // add cashback as fee line item
         // TODO: this should be handled by $order->add_fee after WC 2.2
         $item_id = wc_add_order_item($order_id, array('order_item_name' => __('Cashback', 'woocommerce-pos'), 'order_item_type' => 'fee'));
         if ($item_id) {
             wc_add_order_item_meta($item_id, '_line_total', $cashback);
             wc_add_order_item_meta($item_id, '_line_tax', 0);
             wc_add_order_item_meta($item_id, '_line_subtotal', $cashback);
             wc_add_order_item_meta($item_id, '_line_subtotal_tax', 0);
             wc_add_order_item_meta($item_id, '_tax_class', 'zero-rate');
         }
         // update the order total to include fee
         $order_total = get_post_meta($order_id, '_order_total', true);
         $order_total += $cashback;
         update_post_meta($order_id, '_order_total', $order_total);
     }
     // payment complete
     $order->payment_complete();
     // success
     return array('result' => 'success');
 }
 /**
  *  Main callback function
  * 
  */
 function gocoin_callback()
 {
     if (isset($_GET['gocoin_callback'])) {
         global $woocommerce;
         require plugin_dir_path(__FILE__) . 'gocoin-lib.php';
         $gateways = $woocommerce->payment_gateways->payment_gateways();
         if (!isset($gateways['gocoin'])) {
             return;
         }
         $gocoin = $gateways['gocoin'];
         $response = getNotifyData();
         if (isset($response->error)) {
             var_dump($response);
         } else {
             $orderId = (int) $response->payload->order_id;
             $order = new WC_Order($orderId);
             switch ($response->event) {
                 case 'invoice_created':
                 case 'invoice_payment_received':
                     break;
                 case 'invoice_ready_to_ship':
                     if (in_array($order->status, array('on-hold', 'pending', 'failed'))) {
                         $order->payment_complete();
                     }
                     break;
             }
         }
     }
 }
 public function process_payment($order_id)
 {
     try {
         global $woocommerce;
         $customer_order = new WC_Order($order_id);
         PayU_Middleware::$api_key = $this->api_key;
         PayU_Middleware::$api_login = $this->api_login;
         PayU_Middleware::$merchant_id = $this->merchant_id;
         PayU_Middleware::$account_id = $this->account_id;
         PayU_Middleware::$test_mode = $this->environment == 'yes';
         $cardNumber = str_replace(array(' ', ''), '', $_POST['GP_PayU_online_Gateway-card-number']);
         $expirationArray = explode('/', $_POST['GP_PayU_online_Gateway-card-expiry']);
         $expirationDate = '20' . $expirationArray[1] . '/' . $expirationArray[0];
         $expirationDate = str_replace(' ', '', $expirationDate);
         $payerName = $customer_order->billing_first_name . ' ' . $customer_order->billing_last_name;
         $cvv = $_POST['GP_PayU_online_Gateway-card-cvc'];
         $res = PayU_Middleware::do_payment($order_id, $this->payment_description . $order_id, $customer_order->order_total, $customer_order->billing_email, $payerName, '111', $cardNumber, $cvv, $expirationDate, '', false);
         if (isset($res['code']) == true && isset($res['state']) == true && $res['code'] == 'SUCCESS' && $res['state'] == "APPROVED") {
             do_action('gp_order_online_completed_successfully', $res);
             if ($this->mark_order == 'yes') {
                 $woocommerce->cart->empty_cart();
                 $customer_order->payment_complete();
                 $customer_order->update_status('completed');
             }
             return array('result' => 'success', 'redirect' => $this->thankyou_page_url . '?order_id=' . $order_id);
         } else {
             do_action('gp_order_online_completed_failed', $res);
         }
     } catch (PayUException $e) {
         do_action('gp_error_occurred', $e);
     } catch (Exception $e) {
         do_action('gp_error_occurred', $e);
     }
 }