public function tiago_auto_stock_reduce($order_id)
 {
     $j = get_post_meta($order_id, '_payment_method');
     if ($j[0] == 'pagseguro') {
         $order = new WC_Order($order_id);
         $order->reduce_order_stock();
         // Payment is complete so reduce stock levels
         $order->add_order_note('Estoque reduzido automaticamente ao criar pedido.');
     }
 }
 /**
  * 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);
 }
 /**
  * Process the payment and return the result
  *
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $order = new WC_Order($order_id);
     // Mark as on-hold (we're awaiting the cheque)
     $order->update_status('on-hold', __('Awaiting cheque payment', 'woocommerce'));
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     WC()->cart->empty_cart();
     // Return thankyou redirect
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }
예제 #4
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);
     // Mark as on-hold (we're awaiting the cheque)
     $order->update_status('on-hold', __('Payment to be made upon delivery.', 'woocommerce'));
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     $woocommerce->cart->empty_cart();
     // Empty awaiting payment session
     unset($_SESSION['order_awaiting_payment']);
     // Return thankyou redirect
     return array('result' => 'success', 'redirect' => add_query_arg('key', $order->order_key, add_query_arg('order', $order_id, get_permalink(woocommerce_get_page_id('thanks')))));
 }
 /**
  * Process the pre-order.
  *
  * @param WC_Order $order
  *
  * @return array
  */
 protected function process_pre_order($order_id)
 {
     if (WC_Pre_Orders_Order::order_requires_payment_tokenization($order_id)) {
         try {
             $order = new WC_Order($order_id);
             // Reduce stock levels
             $order->reduce_order_stock();
             // Remove cart
             $this->api->empty_card();
             // Is pre ordered!
             WC_Pre_Orders_Order::mark_order_as_pre_ordered($order);
             // Return thank you page redirect
             return array('result' => 'success', 'redirect' => $this->get_return_url($order));
         } catch (Exception $e) {
             $this->api->add_error('<strong>' . esc_attr($this->title) . '</strong>: ' . $e->getMessage());
             return array('result' => 'fail', 'redirect' => '');
         }
     } else {
         return parent::process_payment($order_id);
     }
 }
 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;
 }
 /**
  * Process the pre-order
  *
  * @param  int $order_id
  * @return array
  */
 public function process_pre_order($order_id)
 {
     if (WC_Pre_Orders_Order::order_requires_payment_tokenization($order_id)) {
         $order = new WC_Order($order_id);
         // Order limit
         if ($order->order_total * 100 < 50) {
             $error_msg = __('Sorry, the minimum allowed order total is 0.50 to use this payment method.', 'woocommerce-payment-gateway-boilerplate');
         }
         if ($this->sandbox == 'yes') {
             $error_msg .= ' ' . __('Developers: Please make sure that you\'re including jQuery and there are no JavaScript errors on the page.', 'woocommerce-payment-gateway-boilerplate');
         }
         // Reduce stock levels
         $order->reduce_order_stock();
         // Remove cart
         WC()->cart->empty_cart();
         // Is pre ordered!
         WC_Pre_Orders_Order::mark_order_as_pre_ordered($order);
         // Return thank you page redirect
         return array('result' => 'success', 'redirect' => $this->get_return_url($order));
         return array('result' => 'fail', 'redirect' => '');
     } else {
         return parent::process_payment($order_id);
     }
 }
	/**
	* 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;
	}
        /**
         * Verify a successful Payment!
         * */
        function check_alphabank_response()
        {
            global $woocommerce;
            global $wpdb;
            //if (( preg_match( '/success/i', $_SERVER['REQUEST_URI'] ) && preg_match( '/alphabank/i', $_SERVER['REQUEST_URI'] ) )) {
            //			$merchantreference= $_GET['MerchantReference'];
            $post_data_array = array();
            if (isset($_POST['mid'])) {
                $post_data_array[0] = $_POST['mid'];
            }
            if (isset($_POST['orderid'])) {
                $post_data_array[1] = $_POST['orderid'];
            }
            if (isset($_POST['status'])) {
                $post_data_array[2] = $_POST['status'];
            }
            if (isset($_POST['orderAmount'])) {
                $post_data_array[3] = $_POST['orderAmount'];
            }
            if (isset($_POST['currency'])) {
                $post_data_array[4] = $_POST['currency'];
            }
            if (isset($_POST['paymentTotal'])) {
                $post_data_array[5] = $_POST['paymentTotal'];
            }
            if (isset($_POST['message'])) {
                $post_data_array[6] = $_POST['message'];
            }
            if (isset($_POST['riskScore'])) {
                $post_data_array[7] = $_POST['riskScore'];
            }
            if (isset($_POST['payMethod'])) {
                $post_data_array[8] = $_POST['payMethod'];
            }
            if (isset($_POST['txId'])) {
                $post_data_array[9] = $_POST['txId'];
            }
            if (isset($_POST['paymentRef'])) {
                $post_data_array[10] = $_POST['paymentRef'];
            }
            $post_data_array[11] = $_POST['digest'];
            $post_DIGEST = $_POST['digest'];
            $post_data = implode("", $post_data_array);
            $digest = base64_encode(sha1(utf8_encode($post_data), true));
            if ($this->mode == "yes") {
                //test mode
                $post_url = 'https://alpha.test.modirum.com/vpos/shophandlermpi';
            } else {
                //live mode
                $post_url = 'https://www.alphaecommerce.gr/vpos/shophandlermpi';
            }
            //
            $ttquery = 'SELECT *
				FROM `' . $wpdb->prefix . 'alphabank_transactions`
				WHERE `orderid` = "' . $_POST['orderid'] . '";';
            $ref = $wpdb->get_results($ttquery);
            $merchantreference = $_GET['MerchantReference'];
            $orderid = $ref['0']->orderid;
            $order = new WC_Order($orderid);
            //$order = $_POST['orderid'];
            if ($_POST['status'] == 'AUTHORIZED' || $_POST['status'] == 'CAPTURED') {
                //verified - successful payment
                //complete order
                if ($order->status == 'processing') {
                    $order->add_order_note(__('Payment Via alphabank<br />Transaction ID: ', 'woocommerce-alphabank-payment-gateway') . $trans_id);
                    //Add customer order note
                    $order->add_order_note(__('Payment Received.<br />Your order is currently being processed.<br />We will be shipping your order to you soon.<br />alphabank Transaction ID: ', 'woocommerce-alphabank-payment-gateway') . $trans_id, 1);
                    // Reduce stock levels
                    $order->reduce_order_stock();
                    // Empty cart
                    WC()->cart->empty_cart();
                    $message = __('Thank you for shopping with us.<br />Your transaction was successful, payment was received.<br />Your order is currently being processed.', 'woocommerce-alphabank-payment-gateway');
                    $message_type = 'success';
                } else {
                    if ($order->has_downloadable_item()) {
                        //Update order status
                        $order->update_status('completed', __('Payment received, your order is now complete.', 'woocommerce-alphabank-payment-gateway'));
                        //Add admin order note
                        $order->add_order_note(__('Payment Via alphabank Payment Gateway<br />Transaction ID: ', 'woocommerce-alphabank-payment-gateway') . $trans_id);
                        //Add customer order note
                        $order->add_order_note(__('Payment Received.<br />Your order is now complete.<br />alphabank Transaction ID: ', 'woocommerce-alphabank-payment-gateway') . $trans_id, 1);
                        $message = __('Thank you for shopping with us.<br />Your transaction was successful, payment was received.<br />Your order is now complete.', 'woocommerce-alphabank-payment-gateway');
                        $message_type = 'success';
                    } else {
                        //Update order status
                        $order->update_status('processing', __('Payment received, your order is currently being processed.', 'woocommerce-alphabank-payment-gateway'));
                        //Add admin order note
                        $order->add_order_note(__('Payment Via alphabank Payment Gateway<br />Transaction ID: ', 'woocommerce-alphabank-payment-gateway') . $trans_id);
                        //Add customer order note
                        $order->add_order_note(__('Payment Received.<br />Your order is currently being processed.<br />We will be shipping your order to you soon.<br />alphabank Transaction ID: ', 'woocommerce-alphabank-payment-gateway') . $trans_id, 1);
                        $message = __('Thank you for shopping with us.<br />Your transaction was successful, payment was received.<br />Your order is currently being processed.', 'woocommerce-alphabank-payment-gateway');
                        $message_type = 'success';
                    }
                    $alphabank_message = array('message' => $message, 'message_type' => $message_type);
                    update_post_meta($order_id, '_alphabank_message', $alphabank_message);
                    // Reduce stock levels
                    $order->reduce_order_stock();
                    // Empty cart
                    WC()->cart->empty_cart();
                }
            } elseif ($_POST['status'] == 'CANCELED') {
                //payment has failed - retry
                $message = __('Thank you for shopping with us. <br />However, the transaction wasn\'t successful, payment wasn\'t received.', 'woocommerce-alphabank-payment-gateway');
                $message_type = 'error';
                $alphabank_message = array('message' => $message, 'message_type' => $message_type);
                update_post_meta($order_id, '_alphabank_message', $pb_message);
                //Update the order status
                $order->update_status('failed', '');
                $checkout_url = $woocommerce->cart->get_checkout_url();
                wp_redirect($checkout_url);
                exit;
            }
            //			elseif ($_POST['status'] == 'CANCELED')
            //			{//an error occurred
            //						$message = __('Thank you for shopping with us. <br />However, an error occurred and the transaction wasn\'t successful, payment wasn\'t received.', 'woocommerce-alphabank-payment-gateway');
            //						$message_type = 'error';
            //						$alphabank_message = array(
            //							'message' => $message,
            //							'message_type' => $message_type
            //						);
            //						update_post_meta($order_id, '_alphabank_message', $pb_message);
            //						//Update the order status
            //						$order->update_status('failed', '');
            //						$checkout_url = $woocommerce->cart->get_checkout_url();
            //						wp_redirect($checkout_url);
            //						exit;
            //			}
            //$this->redirect_page_id = "https://donate.ellak.gr/".get_page_link($this->get_option('redirect_page_id'));
            if ($this->redirect_page_id == "-1") {
                $redirect_url = $this->get_return_url($order);
            } else {
                $redirect_url = $this->redirect_page_id == "" || $this->redirect_page_id == 0 ? get_site_url() . "/" : get_permalink($this->redirect_page_id);
                //For wooCoomerce 2.0
                $redirect_url = add_query_arg(array('msg' => urlencode($this->msg['message']), 'type' => $this->msg['class']), $redirect_url);
            }
            wp_redirect($redirect_url);
            //exit;
            //}
            //		 if(isset($_GET['alphabank'])&& ($_GET['alphabank']==='cancel')) {
            //
            $checkout_url = $woocommerce->cart->get_checkout_url();
            wp_redirect($checkout_url);
            exit;
            //
            //}
        }
 /**
  * Process the payment and return the result
  *
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $order = new WC_Order($order_id);
     // Mark as on-hold (we're awaiting the payment)
     //$order->update_status( 'on-hold', __( 'Awaiting payment', 'woocommerce' ) );
     $statuses = $this->get_order_statuses();
     $note = isset($statuses[$this->default_order_status]) ? $statuses[$this->default_order_status] : '';
     $order->update_status($this->default_order_status, $note);
     if ('yes' === $this->send_email_to_admin || 'yes' === $this->send_email_to_customer) {
         $woocommerce_mailer = WC()->mailer();
         if ('yes' === $this->send_email_to_admin) {
             $woocommerce_mailer->emails['WC_Email_New_Order']->trigger($order_id);
         }
         if ('yes' === $this->send_email_to_customer) {
             $woocommerce_mailer->emails['WC_Email_Customer_Processing_Order']->trigger($order_id);
         }
     }
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     WC()->cart->empty_cart();
     // Return thankyou redirect
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }
 /**
  * Process the payment and redirect.
  *
  * @access public
  * @param  int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $order = new WC_Order($order_id);
     // Mark as 'pending' (we're awaiting the payment)
     $order->update_status('pending', __('Awaiting Stellar payment and verification.', 'woocommerce-stellar-gateway'));
     // Reduce stock levels.
     if ($this->debug != 'yes') {
         $order->reduce_order_stock();
     }
     // Remove cart, leave as is if debugging.
     if ($this->debug != 'yes') {
         WC()->cart->empty_cart();
     }
     // Return to reciept page redirect.
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }
	 public function process_payment( $order_id ) {
		global $woocommerce;
		
		$order = new WC_Order( $order_id );
		
		//get payment tendered amount
		$payment_amount = $_POST['payment_amount'];
		
		//get order total
		$order_total = $order->get_total();
		
		//check for previous payments tendered and add to total payment
		$tendered = get_post_meta( $order->id, 'payment_tendered', true );
		$payment_amount = (float)$payment_amount + (float)$tendered;
			
		//calculate balance after payment applied	
		$balance = $order_total - $payment_amount;
		
		//if payment still needed
		if( $balance > 0 ) {
			
			//document transaction and create order note
			update_post_meta( $order->id, 'payment_tendered', $payment_amount );
			$order->add_order_note( __( '$ ' . round( $payment_amount, 2 ) . ' payment tendered. $ ' . round( $balance, 2 ) . ' remaining.', 'instore' ) );
			$order->update_status('pending', __( 'Awaiting additional payment', 'instore' ) );	
			$payment_complete = false;
			
		} else {
			
			//resuce stock and add order note
			$order->reduce_order_stock();
			$order->add_order_note( __( '$ ' . round( $payment_amount, 2 ) . ' payment Tendered. Change Due $ ' . round( $balance, 2 ) . ' .', 'instore' ) );
			
			//complete order
			$order->payment_complete();
			$payment_complete = true;
			
			//empty cart
			$woocommerce->cart->empty_cart();
		};
		
		//create return array
		$results = array(
			'result'		    => 'success',
			'order_id'		    => $order_id,
			'order_total'	    => $order_total,
			'balance' 		    => $balance,
			'balance_formatted' => wc_price( -$balance ),
			'payment_tendered'  => wc_price( $payment_amount ),
			'payment_complete'  => $payment_complete,
		);
		
		//return results
		return $results;
			
	 }
 public function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $response = simplexml_load_string($this->talk_to_upg($this->get_payment_xml($order_id)));
     if ((string) $response->status == 'OK') {
         $tran_id = sanitize_text_field($response->reference);
         $tran_cv = sanitize_text_field($response->cv2avsresult);
         $tran_ca = sanitize_text_field($response->cardtype);
         $order->reduce_order_stock();
         $woocommerce->cart->empty_cart();
         $order->add_order_note(__('TRANSATION: ' . $tran_id . ' - CV2: ' . $tran_cv . ' - CARD: ' . $tran_ca, 'woothemes'));
         $order->payment_complete($tran_id);
         return array('result' => 'success', 'redirect' => $this->get_return_url($order));
     } else {
         $this->handle_payment_error($response->statustext, $response->reason);
         return;
     }
 }
예제 #14
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);
     // Mark as on-hold (we're awaiting the payment)
     $order->update_status('on-hold', __('Awaiting BACS payment', 'woocommerce'));
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     $woocommerce->cart->empty_cart();
     // Return thankyou redirect
     return array('result' => 'success', 'redirect' => add_query_arg('key', $order->order_key, add_query_arg('order', $order->id, get_permalink(woocommerce_get_page_id('thanks')))));
 }
 /**
  * Process the payment and return the result
  *
  */
 function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     // Mark as on-hold (we're awaiting the invoice)
     $order->update_status('on-hold', __('Awaiting payment', 'dp_wc_invoice'));
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     $woocommerce->cart->empty_cart();
     // Empty awaiting payment session
     unset($woocommerce->session->order_awaiting_payment);
     // Return thankyou redirect
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }
 /**
  * Changes the status for an unpaid, but payment-tokenized order to pre-ordered and adds meta to indicate the order
  * has a payment token. Should be used by supported gateways when processing a pre-order charged upon release, instead of calling
  * $order->payment_complete(), this will be used.
  *
  * @since 1.0
  * @param object|int $order preferably the order object, or order ID if object is inconvenient to provide
  */
 public static function mark_order_as_pre_ordered($order)
 {
     if (!is_object($order)) {
         $order = new WC_Order($order);
     }
     // mark as having a payment token, which will be used upon release to charge pre-order total amount
     update_post_meta($order->id, '_wc_pre_orders_has_payment_token', 1);
     // update status
     $order->update_status('pre-ordered');
     // reduce order stock
     $order->reduce_order_stock();
 }
 /**
  * Hold order and add note
  * @param  WC_Order $order
  * @param  string $reason
  */
 protected function payment_on_hold($order, $reason = '')
 {
     $order->update_status('on-hold', $reason);
     $order->reduce_order_stock();
     WC()->cart->empty_cart();
 }
예제 #18
0
 public function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $order->update_status('pending');
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     $woocommerce->cart->empty_cart();
     return array('result' => 'success', 'redirect' => add_query_arg('order', $order->id, add_query_arg('key', $order->order_key, get_permalink(get_option('woocommerce_pay_page_id')))));
 }
 function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     $order->update_status('on-hold', __('Oczekiwanie na płatność eCard', 'woocommerce'));
     $order->reduce_order_stock();
     $woocommerce->cart->empty_cart();
     return array('result' => 'success', 'redirect' => add_query_arg(array('order_id' => $order_id), $this->notify_link));
 }
 /**
  *      Check payment response from web pay plus
  * */
 function check_webpay_response()
 {
     global $woocommerce;
     global $webpay_comun_folder;
     $SUFIJO = "[WEBPAY - RESPONSE]";
     log_me("Entrando al Webpay Response", $SUFIJO);
     log_me(filter_input_array(INPUT_POST));
     //            log_me("TODOS LOS PARAMETROS", $SUFIJO);
     //            log_me($_REQUEST);
     $TBK_ID_SESION = filter_input(INPUT_POST, "TBK_ID_SESION");
     $TBK_ORDEN_COMPRA = filter_input(INPUT_POST, "TBK_ORDEN_COMPRA");
     if (isset($TBK_ID_SESION) && isset($TBK_ORDEN_COMPRA)) {
         log_me("VARIABLES EXISTENTES", $SUFIJO);
         try {
             $order = new WC_Order($TBK_ORDEN_COMPRA);
             log_me("ORDEN RESCATADA", $SUFIJO);
             $status = filter_input(INPUT_GET, 'status');
             log_me("STATUS " . $status, $SUFIJO);
             if ($order->status !== 'completed') {
                 /**
                  * aquí es donde se hace la validación para la inyección.
                  * 
                  */
                 //Archivo previamente generado para rescatar la información.
                 $myPath = $webpay_comun_folder . DIRECTORY_SEPARATOR . "MAC01Normal{$TBK_ID_SESION}.txt";
                 log_me("INICIANDO LA REVISION MAC PARA " . $myPath, $SUFIJO);
                 //Rescate de los valores informados por transbank
                 $fic = fopen($myPath, "r");
                 $linea = fgets($fic);
                 fclose($fic);
                 $detalle = explode("&", $linea);
                 $TBK = array('TBK_ORDEN_COMPRA' => explode("=", $detalle[0]), 'TBK_TIPO_TRANSACCION' => explode("=", $detalle[1]), 'TBK_RESPUESTA' => explode("=", $detalle[2]), 'TBK_MONTO' => explode("=", $detalle[3]), 'TBK_CODIGO_AUTORIZACION' => explode("=", $detalle[4]), 'TBK_FINAL_NUMERO_TARJETA' => explode("=", $detalle[5]), 'TBK_FECHA_CONTABLE' => explode("=", $detalle[6]), 'TBK_FECHA_TRANSACCION' => explode("=", $detalle[7]), 'TBK_HORA_TRANSACCION' => explode("=", $detalle[8]), 'TBK_ID_TRANSACCION' => explode("=", $detalle[10]), 'TBK_TIPO_PAGO' => explode("=", $detalle[11]), 'TBK_NUMERO_CUOTAS' => explode("=", $detalle[12]));
                 log_me($TBK);
                 /**
                  * si es una inyección, o sea que no pasa primero por el xt_compra, no se genera archivo
                  * "MAC" entonces siempre los valores darán cero, ademas de ver si el estado es "success"
                  * preguntamos si el en el archivo rescatado existe la orden de compra si es asi pasamos a la pagina de exito
                  * 
                  */
                 if ($status == 'success' && $TBK['TBK_ORDEN_COMPRA'][1] == $TBK_ORDEN_COMPRA) {
                     // Si el pago ya fue recibido lo marcamos como procesando.
                     $order->update_status('processing');
                     // Reducimos el stock.
                     $order->reduce_order_stock();
                     // Vaciamos el carrito
                     WC()->cart->empty_cart();
                     //Esto servirá más a futuro :). Por ahora sirve como validación.
                     log_me("INSERTANDO EN LA BDD");
                     $this->add_data_webpayplus($TBK_ORDEN_COMPRA, $TBK);
                     log_me("TERMINANDO INSERSIÓN");
                     /**
                      * en cambio si el status es "failure" o en el archivo MAC no existe la orden de compra, redirigimos a la pagina
                      * de fracaso
                      * 
                      */
                 } elseif ($status == 'failure' || $TBK['TBK_ORDEN_COMPRA'][1] != $TBK_ORDEN_COMPRA) {
                     log_me("FALLO EN EL PAGO DE LA ORDEN", $SUFIJO);
                     $order->update_status('failed');
                     $order->add_order_note('Failed');
                 }
             } else {
                 //Si la orden ya ha sido pagada, redirijo al home para evitar exploit.
                 log_me("Esta orden ya ha sido completada", $SUFIJO);
                 wp_redirect(home_url());
                 exit;
                 //                            add_action('the_content', array(&$this, 'thankyouContent'));
             }
         } catch (Exception $e) {
             log_me("Ha ocurrido un error procesando el pago.", $SUFIJO);
             log_me($e);
             //Si existe un error también redirijo al inicio para evitar exploit.
             wp_redirect(home_url());
             exit;
             //
         }
     } else {
         log_me("FALTAN PARAMETROS", $SUFIJO);
     }
     log_me("SALIENDO DEL RESPONSE", $SUFIJO);
 }
 /**
  *   This is the callback we declared
  *   For sanity we respond HTTP Status 200
  *   You should only print if necesary
  */
 function check_response()
 {
     global $woocommerce;
     global $wpdb;
     error_log("check_response");
     // Load the settings.
     $this->init_settings();
     if ($_POST) {
         error_log("check_response... " . $_POST['action']);
         if ($_POST['action'] === 'openpay_pay_creditcard') {
             $this->openpay_pay_creditcard();
             $order = new WC_Order($_POST["order-id"]);
             $order->update_status('on-hold', 'En espera de pago');
             $order->reduce_order_stock();
             $woocommerce->cart->empty_cart();
             //exit();
             wp_redirect($this->get_return_url($order));
         } elseif ($_POST['action'] === 'openpay_pay_store') {
             $this->openpay_pay_store();
             $order = new WC_Order($_POST["order-id"]);
             $order->update_status('on-hold', 'En espera de pago');
             $order->reduce_order_stock();
             $woocommerce->cart->empty_cart();
             exit;
             wp_redirect($this->get_return_url($order));
         } elseif ($_POST['action'] === 'openpay_pay_transfer') {
             $this->openpay_pay_transfer();
             $order = new WC_Order($_POST["order-id"]);
             $order->update_status('on-hold', 'En espera de pago');
             $order->reduce_order_stock();
             $woocommerce->cart->empty_cart();
             exit;
             wp_redirect($this->get_return_url($order));
         }
     } else {
         header('Content-Type: application/json;charset=utf-8;');
         $data = json_decode(file_get_contents('php://input'));
         $order = new WC_Order($data->transaction->order_id);
         $fetchOption = get_option('openpay_code_private');
         if (update_option('openpay_code_private', $data->verification_code)) {
             $fetchOption2 = " Yes | ";
         } else {
             $fetchOption2 = " No | ";
         }
         $fetchOption2 .= get_option('openpay_code_private');
         $comma_delmited_list = "Response: " . print_r($data, true) . "\n Data:" . print_r($fetchOption, true) . " " . print_r($fetchOption2, true);
         $fp = fopen("array.txt", "a");
         if ($fp == false) {
             //do debugging or logging here
         } else {
             fwrite($fp, $comma_delmited_list);
             fclose($fp);
         }
         if ($data->verification_code) {
             wp_die("Openpay IPN Request Verification Code ->" . $data->verification_code, "Openpay IPN", array('response' => 200));
         } else {
             $status = "";
             $note = "";
             $flag = 0;
             switch ($data->type) {
                 case "charge.succeeded":
                     $order->update_status('processing', "Pago recibido por " . $data->transaction->amount . " id de transacción Openpay " . $data->transaction->id, false);
                     //$order->payment_complete();
                     break;
                 case "charge.cancelled":
                     $order->cancel_order("La orden se cancelo por falta de pago, id Openpay  " . $data->transaction->id);
                     break;
                 case "charge.refunded":
                     $order->add_order_note("El pago se devolcio en Openpay, favor de marcar la orden como cancelada", false);
                     //No se hace nada ya que se tiene que registrar el refund en woocomerce de forma manual
                     break;
             }
             $pays_table = $wpdb->prefix . 'woocommerce_openpay_pays';
             $wpdb->insert($pays_table, array('ID_ORDER' => $data->transaction->order_id, 'ID_OPENPAY_CHARGE' => $data->transaction->id, 'METHOD' => $data->transaction->method, 'STATUS' => $data->transaction->status, 'TYPE' => $data->type, 'CREATED' => $data->event_date), array('%d', '%s', '%s', '%s', '%s'));
             wp_die("Openpay IPN Request Failure", "Openpay IPN", array('response' => 200));
         }
     }
 }
예제 #22
0
function woogiving_process_donation()
{
    // Setup post variables
    $wg_order_id = $_POST['wg_order_id'];
    $jg_donation_id = $_POST['jg_donation_id'];
    if (is_numeric($wg_order_id) && ctype_alnum($jg_donation_id)) {
        // Validate order ID
        $wg_order_id_validation = get_post((int) $wg_order_id);
        if ($wg_order_id_validation) {
            // Get options
            $wg_options = get_option('woocommerce_woogiving_settings');
            // Include JG API and setup API
            require_once 'inc/JustGivingClient.php';
            $jg_client = new JustGivingClient('https://api.justgiving.com/', $wg_options['app_id'], 1, $wg_options['api_login'], $wg_options['api_password']);
            // Check if donation exists in JG
            $wg_donation_id_check = $jg_client->Donation->RetrieveRef(woogiving_create_ref($wg_order_id_validation->ID));
            if (count($wg_donation_id_check->donations)) {
                // Check if donations IDs match
                if ($wg_donation_id_check->donations[0]->id == (int) $jg_donation_id) {
                    // Get donation details from JG
                    $wg_donation_id_status = $jg_client->Donation->RetrieveStatus($jg_donation_id);
                    $jg_amount = $wg_donation_id_status->amount;
                    $jg_status = $wg_donation_id_status->status;
                    // Get customer order
                    $customer_order = new WC_Order($wg_order_id_validation->ID);
                    // Check if amount donated is equal to higher than the amount in the order
                    if ($jg_amount >= $customer_order->order_total && $jg_status == 'Accepted') {
                        // Get JG fundraising page ID
                        $wg_jg_page_check = $jg_client->Page->Retrieve($wg_options['username']);
                        // Check if donation was made to correct charity
                        if ($wg_jg_page_check->charity->id == $wg_donation_id_check->donations[0]->charityId) {
                            // Check order status
                            if ($customer_order->get_status() == 'completed') {
                                // Order has already been completed
                                return json_encode(array('wg_status' => 'failure', 'wg_message' => __('This donation has already been processed.', 'woogiving')));
                            } else {
                                // Reduce stock levels and complete payment
                                $customer_order->reduce_order_stock();
                                $customer_order->payment_complete($jg_donation_id);
                                $customer_order->update_status('completed');
                                return json_encode(array('wg_status' => 'success', 'wg_redirect' => woogiving_get_return_url($customer_order)));
                            }
                        } else {
                            return json_encode(array('wg_status' => 'failure', 'wg_message' => __('This donation cannot be processed, please contact us.', 'woogiving')));
                        }
                    }
                } else {
                    return json_encode(array('wg_status' => 'failure', 'wg_message' => __('Invalid donation ID.', 'woogiving')));
                }
            } else {
                return json_encode(array('wg_status' => 'failure', 'wg_message' => __('Invalid donation ID.', 'woogiving')));
            }
        } else {
            return json_encode(array('wg_status' => 'failure', 'wg_message' => __('Donation could not be processed.', 'woogiving')));
        }
    } else {
        return json_encode(array('wg_status' => 'failure', 'wg_message' => __('Donation could not be processed.', 'woogiving')));
    }
}
예제 #23
0
 /**
  * @param WC_Order $order
  * @param string $new_status
  * @param string $note
  */
 public function updateOrderStatus(WC_Order $order, $new_status, $note = '')
 {
     $order->update_status($new_status, $note);
     switch ($new_status) {
         case self::STATUS_ON_HOLD:
             if (!get_post_meta($order->id, '_order_stock_reduced', $single = true)) {
                 // Reduce order stock
                 $order->reduce_order_stock();
                 Mollie_WC_Plugin::debug(__METHOD__ . ":  Stock for order {$order->id} reduced.");
             }
             break;
         case self::STATUS_PENDING:
         case self::STATUS_FAILED:
         case self::STATUS_CANCELLED:
             if (get_post_meta($order->id, '_order_stock_reduced', $single = true)) {
                 // Restore order stock
                 Mollie_WC_Plugin::getDataHelper()->restoreOrderStock($order);
                 Mollie_WC_Plugin::debug(__METHOD__ . " Stock for order {$order->id} restored.");
             }
             break;
     }
 }
 /**
  * Check Pagantis response
  */
 function check_rds_response()
 {
     global $woocommerce;
     $json = file_get_contents('php://input');
     $temp = json_decode($json, true);
     $this->environment == 'Test' ? $this->key = $this->test_key : ($this->key = $this->real_key);
     $signature_check = sha1($this->key . $temp['account_id'] . $temp['api_version'] . $temp['event'] . $temp['data']['id']);
     if ($signature_check != $temp['signature']) {
         //hack detected - not implemented yet
         wp_die('<b>PagaMasTarde</b>: Fallo en el proceso de pago.<br>Su pedido ha sido cancelado.
         <a style="clear:both" href ="' . home_url('/') . '" > Volver </a>');
     }
     $data = $temp['data'];
     if (!empty($data)) {
         $orderId = $data['order_id'];
         $order = new WC_Order($orderId);
         $this->log->add('pagantis', 'Paga+Tarde notification received for orderId:' . $orderId);
         switch ($temp['event']) {
             case 'charge.created':
                 $order->update_status('processing', __('Pago realizo con Pagantis', 'woocommerce'));
                 $this->log->add('pagantis', 'Operación finalizada. PEDIDO ACEPTADO:' . $orderId);
                 $order->reduce_order_stock();
                 // Remove cart
                 WC()->cart->empty_cart();
                 wp_redirect($this->get_return_url($order));
                 break;
             case 'charge.failed':
                 $order->update_status('cancelled', __('Error en el pago con Pagantis', 'woocommerce'));
                 $this->log->add('pagantis', 'Operación finalizada. PEDIDO CANCELADO' . $orderId);
                 wp_redirect($order->get_cancel_order_url());
                 break;
         }
     } else {
         wp_die('<b>PagaMasTarde</b>: Fallo en el proceso de pago.<br>Su pedido ha sido cancelado.
         <a style="clear:both" href ="' . home_url('/') . '" > Volver </a>');
     }
 }
 /**
  * Process the pre-order.
  *
  * @param WC_Order $order
  * @param string   $cart_token
  * @uses  Simplify_ApiException
  * @uses  Simplify_BadRequestException
  * @return array
  */
 protected function process_pre_order($order, $cart_token = '')
 {
     if (WC_Pre_Orders_Order::order_requires_payment_tokenization($order->id)) {
         try {
             if ($order->order_total * 100 < 50) {
                 $error_msg = __('Sorry, the minimum allowed order total is 0.50 to use this payment method.', 'woocommerce');
                 throw new Simplify_ApiException($error_msg);
             }
             if (empty($cart_token)) {
                 $error_msg = __('Please make sure your card details have been entered correctly and that your browser supports JavaScript.', 'woocommerce');
                 if ('yes' == $this->sandbox) {
                     $error_msg .= ' ' . __('Developers: Please make sure that you\'re including jQuery and there are no JavaScript errors on the page.', 'woocommerce');
                 }
                 throw new Simplify_ApiException($error_msg);
             }
             // Create customer
             $customer = Simplify_Customer::createCustomer(array('token' => $cart_token, 'email' => $order->billing_email, 'name' => trim($order->get_formatted_billing_full_name()), 'reference' => $order->id));
             if (is_object($customer) && '' != $customer->id) {
                 $customer_id = wc_clean($customer->id);
                 // Store the customer ID in the order
                 update_post_meta($order->id, '_simplify_customer_id', $customer_id);
             } else {
                 $error_msg = __('Error creating user in Simplify Commerce.', 'woocommerce');
                 throw new Simplify_ApiException($error_msg);
             }
             // Reduce stock levels
             $order->reduce_order_stock();
             // Remove cart
             WC()->cart->empty_cart();
             // Is pre ordered!
             WC_Pre_Orders_Order::mark_order_as_pre_ordered($order);
             // Return thank you page redirect
             return array('result' => 'success', 'redirect' => $this->get_return_url($order));
         } catch (Simplify_ApiException $e) {
             if ($e instanceof Simplify_BadRequestException && $e->hasFieldErrors() && $e->getFieldErrors()) {
                 foreach ($e->getFieldErrors() as $error) {
                     wc_add_notice($error->getFieldName() . ': "' . $error->getMessage() . '" (' . $error->getErrorCode() . ')', 'error');
                 }
             } else {
                 wc_add_notice($e->getMessage(), 'error');
             }
             return array('result' => 'fail', 'redirect' => '');
         }
     } else {
         return parent::process_standard_payments($order, $cart_token);
     }
 }
 /**
  * Process the payment
  * @param  integer $order_id
  * @return array   result & redirect URL
  */
 function process_payment($order_id)
 {
     // WooCommerce global
     global $woocommerce;
     // Require Triveneto class
     require 'PgConsTriv.php';
     // Get Order Object
     $order = new WC_Order($order_id);
     // init PgConsTriv Class for PaymentInit (action Purchase)
     $pg = new PgConsTriv(ICL_LANGUAGE_CODE, $this->settings);
     $pg->setAction('Purchase');
     // Payment Provider response will be sent to our triveneto_response_interface
     // Which is defined in 'woocommerce-triveneto-gateway.php'
     $pg->setResponseURL(get_home_url() . '/?triveneto_response_interface=1');
     // Define the goto URL if something goes wrong
     $pg->setErrorURL($order->get_cancel_order_url());
     // Send the message of PaymentInit
     $amount = $woocommerce->cart->get_cart_total();
     $amount = floatval(preg_replace('#[^\\d.]#', '', $amount));
     // parse numbers
     $tracking_id = $order_id;
     $pg->sendVal_PI($amount, $tracking_id);
     // Get result of request
     $hasError = $pg->hasError_PI();
     $ID_PI = $pg->getID_PI();
     // Check for errors
     if ($hasError) {
         $errorCode = $pg->getError_PI();
         // Cancel process and redirect to other page:
         return array('result' => 'error', 'redirect' => $order->get_cancel_order_url());
     }
     // Mark as on-hold (we're awaiting the cheque)
     $order->update_status('on-hold', __('Awaiting TrivenetoBassilichi payment', 'woocommerce_gateway_tvb'));
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     $woocommerce->cart->empty_cart();
     // Get the payment URL for the customer:
     $paymentURL = $pg->getPaymentURL_PI();
     // Send to payment URL
     return array('result' => 'success', 'redirect' => $paymentURL);
 }
 /**
  * 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;
 }
function YMcheckPayment()
{
    global $wpdb;
    // if ($_REQUEST['yandex_money'] == 'hash') {
    // echo md5('');
    // }
    if ($_REQUEST['yandex_money'] == 'check') {
        $hash = md5($_POST['action'] . ';' . $_POST['orderSumAmount'] . ';' . $_POST['orderSumCurrencyPaycash'] . ';' . $_POST['orderSumBankPaycash'] . ';' . $_POST['shopId'] . ';' . $_POST['invoiceId'] . ';' . $_POST['customerNumber'] . ';' . get_option('ym_shopPassword'));
        header('Content-Type: application/xml');
        if (strtolower($hash) != strtolower($_POST['md5']) and isset($_POST['md5'])) {
            // !=
            $code = 1;
            echo '<?xml version="1.0" encoding="UTF-8"?><checkOrderResponse performedDatetime="' . $_POST['requestDatetime'] . '" code="' . $code . '"' . ' invoiceId="' . $_POST['invoiceId'] . '" shopId="' . get_option('ym_ShopID') . '" message="bad md5"/>';
        } else {
            $order = $wpdb->get_row('SELECT * FROM ' . $wpdb->prefix . 'posts WHERE ID = ' . (int) $_POST['customerNumber']);
            $order_summ = get_post_meta($order->ID, '_order_total', true);
            if (!$order) {
                $code = 200;
                $answer = '<?xml version="1.0" encoding="UTF-8"?><checkOrderResponse performedDatetime="' . $_POST['requestDatetime'] . '" code="' . $code . '"' . ' invoiceId="' . $_POST['invoiceId'] . '" shopId="' . get_option('ym_ShopID') . '" message="wrong customerNumber"/>';
            } elseif ($order_summ != $_POST['orderSumAmount']) {
                // !=
                $code = 100;
                $answer = '<?xml version="1.0" encoding="UTF-8"?><checkOrderResponse performedDatetime="' . $_POST['requestDatetime'] . '" code="' . $code . '"' . ' invoiceId="' . $_POST['invoiceId'] . '" shopId="' . get_option('ym_ShopID') . '" message="wrong orderSumAmount"/>';
            } else {
                $code = 0;
                if ($_POST['action'] == 'paymentAviso') {
                    $order_w = new WC_Order($order->ID);
                    $order_w->update_status('processing', __('Awaiting BACS payment', 'woocommerce'));
                    $order_w->reduce_order_stock();
                    $answer = '<?xml version="1.0" encoding="UTF-8"?><paymentAvisoResponse performedDatetime="' . date('c') . '" code="' . $code . '" invoiceId="' . $_POST['invoiceId'] . '" shopId="' . get_option('ym_ShopID') . '" />';
                } else {
                    $answer = '<?xml version="1.0" encoding="UTF-8"?><checkOrderResponse performedDatetime="' . date('c') . '" code="' . $code . '" invoiceId="' . $_POST['invoiceId'] . '" shopId="' . get_option('ym_ShopID') . '" />';
                }
            }
        }
        die($answer);
    }
}
 /**
  * Process the payment and return the result
  *
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     $order = new WC_Order($order_id);
     // Mark as processing (payment won't be taken until delivery)
     $order->update_status('processing', __('Payment to be made upon delivery.', 'woocommerce'));
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     WC()->cart->empty_cart();
     // Return thankyou redirect
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }
 /**
  * Process the payment and return the result
  *
  * @since 1.0
  * @param int $order_id
  * @return array
  */
 public function process_payment($order_id)
 {
     global $woocommerce;
     $order = new WC_Order($order_id);
     // Reduce stock levels
     $order->reduce_order_stock();
     // Remove cart
     $woocommerce->cart->empty_cart();
     // Update status
     $order->update_status('pre-ordered');
     // Redirect to thank you page
     return array('result' => 'success', 'redirect' => $this->get_return_url($order));
 }