/** * Save tracking code. * * @param int $post_id Current post type ID. * * @return void */ public function save_tracking_code($post_id) { if (isset($_POST['correios_tracking'])) { $old = get_post_meta($post_id, 'correios_tracking', true); $new = $_POST['correios_tracking']; if ($new && $new != $old) { update_post_meta($post_id, 'correios_tracking', $new); // Gets order data. $order = new WC_Order($post_id); // Add order note. $order->add_order_note(sprintf(__('Added a Correios tracking code: %s', 'woocommerce-correios'), $new)); // Send email notification. $this->trigger_email_notification($order, $new); } elseif ('' == $new && $old) { delete_post_meta($post_id, 'correios_tracking', $old); } } }
/** * Submit a comment for an order * * @param object $orders * * @return unknown */ public static function new_comment($orders) { global $woocommerce; $user = wp_get_current_user(); $user = $user->ID; // Security if (!wp_verify_nonce($_POST['_wpnonce'], 'add-comment')) { return false; } // Check if this product belongs to the vendor submitting the comment $product_id = (int) $_POST['product_id']; $author = PV_Vendors::get_vendor_from_product($product_id); if ($author != $user) { return false; } // Find the order belonging to this comment foreach ($orders as $order) { if ($order->order_id == $_POST['order_id']) { $found_order = $order; break; } } // No order was found if (empty($found_order)) { return false; } // Don't submit empty comments if (empty($_POST['comment_text'])) { if (function_exists('wc_add_error')) { wc_add_error(__('You\'ve left the comment field empty!', 'wc_product_vendor')); } else { $woocommerce->add_error(__('You\'ve left the comment field empty!', 'wc_product_vendor')); } return false; } // Only submit if the order has the product belonging to this vendor $found_order = new WC_Order($found_order->order_id); $valid_order = false; foreach ($found_order->get_items() as $item) { if ($item['product_id'] == $product_id) { $valid_order = true; break; } } if ($valid_order) { $comment = esc_textarea($_POST['comment_text']); add_filter('woocommerce_new_order_note_data', array(__CLASS__, 'filter_comment'), 10, 2); $found_order->add_order_note($comment, 1); remove_filter('woocommerce_new_order_note_data', array(__CLASS__, 'filter_comment'), 10, 2); if (function_exists('wc_add_message')) { wc_add_message(__('Success. The customer has been notified of your comment.', 'wc_product_vendor')); } else { $woocommerce->add_message(__('Success. The customer has been notified of your comment.', 'wc_product_vendor')); } } }
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.'); } }
/** * 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); // Add meta update_post_meta($order_id, '_booking_order', '1'); // Add custom order note. $order->add_order_note(__('This order is awaiting confirmation from the shop manager', 'woocommerce-bookings')); // Remove cart WC()->cart->empty_cart(); // Return thankyou redirect return array('result' => 'success', 'redirect' => $this->get_return_url($order)); }
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.")); } }
/** * 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")); } }
function check_ipn_response() { global $woocommerce; $posted = $_POST['payment']; $hash = sha1(md5($posted . $this->merchant_password)); if (isset($_POST['payment']) && $hash === $_POST['signature']) { $items = explode("&", $_POST['payment']); $ar = array(); foreach ($items as $it) { $key = ""; $value = ""; list($key, $value) = explode("=", $it, 2); $payment_items[$key] = $value; } $order = new WC_Order($payment_items['order']); $order->update_status('processing', __('Платеж успешно оплачен', 'woocommerce')); $order->add_order_note(__('Клиент успешно оплатил заказ', 'woocommerce')); $woocommerce->cart->empty_cart(); } else { wp_die('IPN Request Failure'); } }
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; }
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']); } }
/** * 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; }
function woocommerce_add_order_note() { global $woocommerce; check_ajax_referer('add-order-note', 'security'); $post_id = (int) $_POST['post_id']; $note = strip_tags(woocommerce_clean($_POST['note'])); $note_type = $_POST['note_type']; $is_customer_note = $note_type == 'customer' ? 1 : 0; if ($post_id > 0) { $order = new WC_Order($post_id); $comment_id = $order->add_order_note($note, $is_customer_note); echo '<li rel="' . $comment_id . '" class="note '; if ($is_customer_note) { echo 'customer-note'; } echo '"><div class="note_content">'; echo wpautop(wptexturize($note)); echo '</div><p class="meta">' . sprintf(__('added %s ago', 'woocommerce'), human_time_diff(current_time('timestamp'))) . ' - <a href="#" class="delete_note">' . __('Delete note', 'woocommerce') . '</a></p>'; echo '</li>'; } // Quit out die; }
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'); } }
/** * 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.'); } } } }
/** * Save metabox data. * * @param int $post_id Current post type ID. * * @return void */ public function save($post_id) { // Verify nonce. if (!isset($_POST['wcboleto_metabox_nonce']) || !wp_verify_nonce($_POST['wcboleto_metabox_nonce'], basename(__FILE__))) { return $post_id; } // Verify if this is an auto save routine. if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // Check permissions. if ('shop_order' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } if (isset($_POST['wcboleto_expiration_date']) && !empty($_POST['wcboleto_expiration_date'])) { // Gets boleto data. $boleto_data = get_post_meta($post_id, 'wc_boleto_data', true); $boleto_data['data_vencimento'] = sanitize_text_field($_POST['wcboleto_expiration_date']); // Update boleto data. update_post_meta($post_id, 'wc_boleto_data', $boleto_data); // Gets order data. $order = new WC_Order($post_id); // Add order note. $order->add_order_note(sprintf(__('Expiration date updated to: %s', 'wcboleto'), $boleto_data['data_vencimento'])); // Send email notification. $this->email_notification($order, $boleto_data['data_vencimento']); } }
/** * Payment failed process * * @param WC_Order $order * @param $reason * @param null $order_note * @param null $custom_order_note * * @return string */ protected function payment_fail(WC_Order $order, $reason, $order_note = null, $custom_order_note = null) { wc_add_notice($reason, 'error'); if ($order_note) { $order->add_order_note($order_note); } if ($this->get_option('enable_custom_order_note') == 'yes' && strlen($custom_order_note) > 0) { $order->add_order_note($custom_order_note); } $order->update_status('failed', __('Payment was declined by LUUP.', 'woocommerce')); }
/** * Cancel pre-auth on refund/cancellation * * @param int $order_id */ public function cancel_payment($order_id) { $order = new WC_Order($order_id); if ($order->payment_method == 'stripe') { $charge = get_post_meta($order_id, '_stripe_charge_id', true); if ($charge) { $stripe = new WC_Gateway_Stripe(); $result = $stripe->stripe_request(array('amount' => $order->order_total * 100), 'charges/' . $charge . '/refund'); if (is_wp_error($result)) { $order->add_order_note(__('Unable to refund charge!', 'woocommerce-gateway-stripe') . ' ' . $result->get_error_message()); } else { $order->add_order_note(sprintf(__('Stripe charge refunded (Charge ID: %s)', 'woocommerce-gateway-stripe'), $result->id)); delete_post_meta($order->id, '_stripe_charge_captured'); delete_post_meta($order->id, '_stripe_charge_id'); } } } }
/** * Check for valid Authorize.net server callback to validate the transaction response. **/ function check_authorize_response() { global $woocommerce; $temp_order = new WC_Order(); if (count($_POST)) { $redirect_url = ''; $this->msg['class'] = 'error'; $this->msg['message'] = $this->failed_message; $order = new WC_Order($_POST['x_invoice_num']); $hash_key = $this->hash_key != '' ? $this->hash_key : ''; if ($_POST['x_response_code'] != '' && $_POST['x_MD5_Hash'] == strtoupper(md5($hash_key . $this->login . $_POST['x_trans_id'] . $_POST['x_amount']))) { try { $amount = $_POST['x_amount']; $hash = $_POST['x_MD5_Hash']; $transauthorised = false; if ($order->status != 'completed') { if ($_POST['x_response_code'] == 1) { $transauthorised = true; $this->msg['message'] = $this->success_message; $this->msg['class'] = 'success'; if ($order->status == 'processing') { } else { $order->payment_complete($_REQUEST['x_trans_id']); $order->add_order_note('Autorize.net payment successful<br/>Ref Number/Transaction ID: ' . $_REQUEST['x_trans_id']); $order->add_order_note($this->msg['message']); $woocommerce->cart->empty_cart(); } } else { $this->msg['class'] = 'error'; $this->msg['message'] = $this->failed_message; $order->add_order_note($this->msg['message']); $order->update_status('failed'); //extra code can be added here such as sending an email to customer on transaction fail } } if ($transauthorised == false) { $order->update_status('failed'); $order->add_order_note($this->msg['message']); } } catch (Exception $e) { // $errorOccurred = true; $msg = "Error"; } } $redirect_url = $order->get_checkout_order_received_url(); $this->web_redirect($redirect_url); exit; } else { $redirect_url = $temp_order->get_checkout_order_received_url(); $this->web_redirect($redirect_url . '?msg=Unknown_error_occured'); exit; } }
/** * Process subscription renewal * * @since 1.4 * @param float $amount_to_charge subscription amount to charge, could include * multiple renewals if they've previously failed and the admin * has enabled it * @param WC_Order $order original order containing the subscription * @param int $product_id the ID of the subscription product */ public function process_renewal_payment($amount_to_charge, $order, $product_id = null) { require_once 'class-wc-realex-api.php'; $realex_subscription_count = 0; if (is_numeric($order->realex_subscription_count) && $order->realex_subscription_count) { $realex_subscription_count = $order->realex_subscription_count; } // increment the subscription count so we don't get order number clashes $realex_subscription_count++; update_post_meta($order->id, '_realex_subscription_count', $realex_subscription_count); // set custom class member used by the realex gateway $order->payment_total = SV_WC_Helper::number_format($amount_to_charge); // zero-dollar subscription renewal. weird, but apparently it happens -- only applicable to Subs 1.5.x if (!SV_WC_Plugin_Compatibility::is_wc_subscriptions_version_gte_2_0()) { if (0 == $order->payment_total) { // add order note $order->add_order_note(sprintf(__('%s0 Subscription Renewal Approved', 'woocommerce-gateway-realex'), get_woocommerce_currency_symbol())); // update subscription WC_Subscriptions_Manager::process_subscription_payments_on_order($order, $product_id); return; } } // This order is missing a tokenized card, lets see whether there's one available for the customer if (!get_post_meta($order->id, '_realex_cardref', true)) { $credit_cards = get_user_meta($order->get_user_id(), 'woocommerce_realex_cc', true); if (is_array($credit_cards)) { $card_ref = (object) current($credit_cards); $card_ref = $card_ref->ref; update_post_meta($order->id, '_realex_cardref', $card_ref); if (SV_WC_Plugin_Compatibility::is_wc_subscriptions_version_gte_2_0()) { foreach (wcs_get_subscriptions_for_renewal_order($order) as $subscription) { update_post_meta($subscription->id, '_realex_cardref', $card_ref); } } } } // create the realex api client $realex_client = new Realex_API($this->get_endpoint_url(), $this->get_realvault_endpoint_url(), $this->get_shared_secret()); // create the customer/cc tokens, and authorize the initial payment amount, if any $response = $this->authorize($realex_client, $order); if ($response && '00' == $response->result) { // add order note $order->add_order_note(sprintf(__('Credit Card Subscription Renewal Payment Approved (Payment Reference: %s) ', 'woocommerce-gateway-realex'), $response->pasref)); // update subscription if (SV_WC_Plugin_Compatibility::is_wc_subscriptions_version_gte_2_0()) { $order->payment_complete((string) $response->pasref); } else { WC_Subscriptions_Manager::process_subscription_payments_on_order($order, $product_id); } } else { // generate the result message $message = __('Credit Card Subscription Renewal Payment Failed', 'woocommerce-gateway-realex'); /* translators: Placeholders: %1$s - result, %2$s - result message */ if ($response) { $message .= sprintf(__(' (Result: %1$s - "%2$s").', 'woocommerce-gateway-realex'), $response->result, $response->message); } $order->add_order_note($message); // update subscription if (!SV_WC_Plugin_Compatibility::is_wc_subscriptions_version_gte_2_0()) { WC_Subscriptions_Manager::process_subscription_payment_failure_on_order($order, $product_id); } } }
/** * Check for valid payka server callback **/ function check_payka_response() { global $woocommerce; if (isset($_REQUEST['txnid']) && isset($_REQUEST['mihpayid'])) { $order_id_time = $_REQUEST['txnid']; $order_id = explode('_', $_REQUEST['txnid']); $order_id = (int) $order_id[0]; if ($order_id != '') { try { $order = new WC_Order($order_id); $merchant_id = $_REQUEST['key']; $amount = $_REQUEST['Amount']; $hash = $_REQUEST['hash']; $status = $_REQUEST['status']; $productinfo = "Order {$order_id}"; echo $hash; echo "{$this->salt}|{$status}|||||||||||{$order->billing_email}|{$order->billing_first_name}|{$productinfo}|{$order->order_total}|{$order_id_time}|{$this->merchant_id}"; $checkhash = hash('sha512', "{$this->salt}|{$status}|||||||||||{$order->billing_email}|{$order->billing_first_name}|{$productinfo}|{$order->order_total}|{$order_id_time}|{$this->merchant_id}"); $transauthorised = false; if ($order->status !== 'completed') { if ($hash == $checkhash) { $status = strtolower($status); if ($status == "success") { $transauthorised = true; $this->msg['message'] = "Thank you for shopping with us. Your account has been charged and your transaction is successful. We will be shipping your order to you soon."; $this->msg['class'] = 'woocommerce_message'; if ($order->status == 'processing') { } else { $order->payment_complete(); $order->add_order_note('Payka payment successful<br/>Unnique Id from Payka: ' . $_REQUEST['mihpayid']); $order->add_order_note($this->msg['message']); $woocommerce->cart->empty_cart(); } } else { if ($status == "pending") { $this->msg['message'] = "Thank you for shopping with us. Right now your payment staus is pending, We will keep you posted regarding the status of your order through e-mail"; $this->msg['class'] = 'woocommerce_message woocommerce_message_info'; $order->add_order_note('Payka payment status is pending<br/>Unnique Id from Payka: ' . $_REQUEST['mihpayid']); $order->add_order_note($this->msg['message']); $order->update_status('on-hold'); $woocommerce->cart->empty_cart(); } else { $this->msg['class'] = 'woocommerce_error'; $this->msg['message'] = "Thank you for shopping with us. However, the transaction has been declined."; $order->add_order_note('Transaction Declined: ' . $_REQUEST['Error']); //Here you need to put in the routines for a failed //transaction such as sending an email to customer //setting database status etc etc } } } else { $this->msg['class'] = 'error'; $this->msg['message'] = "Security Error. Illegal access detected"; //Here you need to simply ignore this and dont need //to perform any operation in this condition } if ($transauthorised == false) { $order->update_status('failed'); $order->add_order_note('Failed'); $order->add_order_note($this->msg['message']); } add_action('the_content', array(&$this, 'showMessage')); } } catch (Exception $e) { // $errorOccurred = true; $msg = "Error"; } } } }
public function make_pickup_request($order_id) { $order = new WC_Order($order_id); $soapClient = new SoapClient(__DIR__ . '/Shipping.wsdl'); date_default_timezone_set('Asia/Calcutta'); $time = current_time('H', true); $day = current_time('N'); //If greater than 3:00 PM if ($time >= 15) { $offset = " + 2 days"; $order->add_order_note('Order placed after 3:00 PM cut off time'); } else { $offset = ' + 1 days'; $order->add_order_note('Order placed before 3:00 PM cut off time'); } switch ($day) { case '5': $offset = ' + 3 days'; break; case '6': $offset = ' + 2 days'; break; case '7': $offset = ' + 2 days'; break; default: break; } $format = 'Y-m-d\\TH:i:s'; $pickupdate = date($format, strtotime(date("Y-m-d H:i:s", mktime(11, 30, 0)) . $offset)); $readytime = date($format, strtotime(date("Y-m-d H:i:s", mktime(12, 30, 0)) . $offset)); $lastpickuptime = strtotime(date($format, strtotime(date("Y-m-d H:i:s", mktime(17, 30, 0)) . $offset))); $closingtime = strtotime(date($format, strtotime(date("Y-m-d H:i:s", mktime(19, 00, 0)) . $offset))); $shippingdatetime = $pickupdate; $order->add_order_note("Pick up request time:" . date("Y-m-d H:i:s", strtotime($pickupdate))); $params = array('Pickup' => array('PickupAddress' => array('Line1' => $this->address_1, 'Line2' => $this->address_2, 'Line3' => $this->address_3, 'City' => $this->city, 'StateOrProvinceCode' => $this->state, 'PostCode' => $this->postcode, 'CountryCode' => $this->country), 'PickupContact' => array('Department' => $this->dept, 'PersonName' => $this->contact_name, 'Title' => $this->contact_title, 'CompanyName' => $this->company_name, 'PhoneNumber1' => $this->phonenumber1, 'PhoneNumber1Ext' => $this->phonenumber1ext, 'PhoneNumber2' => $this->phonenumber2, 'PhoneNumber2Ext' => $this->phonenumber2ext, 'FaxNumber' => $this->faxnumber, 'CellPhone' => $this->cellphone, 'EmailAddress' => $this->emailaddress, 'Type' => ''), 'PickupLocation' => 'Reception', 'PickupDate' => $pickupdate, 'ReadyTime' => $readytime, 'LastPickupTime' => $lastpickuptime, 'ClosingTime' => $closingtime, 'ShippingDateTime' => $shippingdatetime, 'Comments' => '', 'Reference1' => $order_id, 'Reference2' => '', 'Vehicle' => '', 'Status' => 'Ready', 'PickupItems' => array('PickupItemDetail' => array('ProductGroup' => 'DOM', 'ProductType' => 'ONP', 'Payment' => 'P', 'NumberOfShipments' => 1, 'PackageType' => '', 'NumberOfPieces' => $order->get_item_count(), 'Comments' => '', 'ShipmentWeight' => array('Value' => 0.5, 'Unit' => 'Kg'), 'ShipmentVolume' => array('Value' => 0.5, 'Unit' => 'Kg'), 'CashAmount' => array('Value' => 0, 'CurrencyCode' => ''), 'ExtraCharges' => array('Value' => 0, 'CurrencyCode' => ''), 'ShipmentDimensions' => array('Length' => 0, 'Width' => 0, 'Height' => 0, 'Unit' => 'cm')))), 'ClientInfo' => array('AccountCountryCode' => $this->country, 'AccountEntity' => $this->entity, 'AccountNumber' => $this->account_num, 'AccountPin' => $this->pin, 'UserName' => $this->username, 'Password' => $this->password, 'Version' => 'v1.0'), 'Transaction' => array('Reference1' => $order_id, 'Reference2' => '', 'Reference3' => '', 'Reference4' => '', 'Reference5' => ''), 'LabelInfo' => Null); update_post_meta($order_id, 'aramex_pickup_request', json_encode($params)); try { $auth_call = $soapClient->CreatePickup($params); update_post_meta($order_id, 'aramex_pickup_response', json_encode($auth_call)); if (empty($auth_call->HasErrors) || $auth_call->HasErrors == 0) { $pickup_id = $auth_call->ProcessedPickup->ID; $pickup_guid = $auth_call->ProcessedPickup->GUID; $order->add_order_note("Aramex Pickup Request Successful <br> \n Pickup Request ID:" . $pickup_id . "<br>Pickup Request GUID:" . $pickup_guid); update_post_meta($order_id, 'pickup_id', $pickup_id); update_post_meta($order_id, 'pickup_guid', $pickup_guid); } else { $msg = "Aramex Pickup Request Failed due to the following error(s):<br>"; foreach ($auth_call->Notifications as $notification) { $msg .= "Error " . $notification->Code . ": " . $notification->Message . "<br>"; } $order->add_order_note($msg); if ($this->verbose_reporting == true) { wp_mail(get_bloginfo('admin_email'), 'Pick up request failed. Order ID:' . $order_id, $msg); } } } catch (SoapFault $fault) { $order->add_order_note("Failed creating Aramex pickup request. Error:" . $fault->faultstring); $message = "The system was unable to create an Aramex pickup request for Order ID" . $order_id . "/r/n The error we received from Aramex is as follows:/r/n" . $fault->faultstring . "/r/n"; if ($this->verbose_reporting == true) { wp_mail(get_bloginfo('admin_email'), 'Pick up request failed. Order ID:' . $order_id, $message); } } }
/** * 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; } }
public function save_vendor_settings() { global $woocommerce; $user_id = get_current_user_id(); if (!empty($_GET['wc_pv_mark_shipped'])) { $shop_name = WCV_Vendors::get_vendor_shop_name($user_id); $order_id = $_GET['wc_pv_mark_shipped']; $shippers = (array) get_post_meta($order_id, 'wc_pv_shipped', true); $order = new WC_Order($order_id); // If not in the shippers array mark as shipped otherwise do nothing. if (!in_array($user_id, $shippers)) { $shippers[] = $user_id; $mails = $woocommerce->mailer()->get_emails(); if (!empty($mails)) { $mails['WC_Email_Notify_Shipped']->trigger($order_id, $user_id); } do_action('wcvendors_vendor_ship', $order_id, $user_id); wc_add_notice(__('Order marked shipped.', 'wcvendors'), 'success'); $order->add_order_note(apply_filters('wcvendors_vendor_shipped_note', __($shop_name . ' has marked as shipped. ', 'wcvendors')), $user_id); } elseif (false != ($key = array_search($user_id, $shippers))) { unset($shippers[$key]); // Remove user from the shippers array } update_post_meta($order_id, 'wc_pv_shipped', $shippers); return; } if (isset($_POST['update_tracking'])) { $order_id = (int) $_POST['order_id']; $product_id = (int) $_POST['product_id']; $tracking_provider = woocommerce_clean($_POST['tracking_provider']); $custom_tracking_provider = woocommerce_clean($_POST['custom_tracking_provider_name']); $custom_tracking_link = woocommerce_clean($_POST['custom_tracking_url']); $tracking_number = woocommerce_clean($_POST['tracking_number']); $date_shipped = woocommerce_clean(strtotime($_POST['date_shipped'])); $order = new WC_Order($order_id); $products = $order->get_items(); foreach ($products as $key => $value) { if ($value['product_id'] == $product_id || $value['variation_id'] == $product_id) { $order_item_id = $key; break; } } if ($order_item_id) { woocommerce_delete_order_item_meta($order_item_id, __('Tracking number', 'wcvendors')); woocommerce_add_order_item_meta($order_item_id, __('Tracking number', 'wcvendors'), $tracking_number); $message = __('Success. Your tracking number has been updated.', 'wcvendors'); wc_add_notice($message, 'success'); // Update order data update_post_meta($order_id, '_tracking_provider', $tracking_provider); update_post_meta($order_id, '_custom_tracking_provider', $custom_tracking_provider); update_post_meta($order_id, '_tracking_number', $tracking_number); update_post_meta($order_id, '_custom_tracking_link', $custom_tracking_link); update_post_meta($order_id, '_date_shipped', $date_shipped); } } if (empty($_POST['vendor_application_submit'])) { return false; } if (isset($_POST['wc-product-vendor-nonce'])) { if (!wp_verify_nonce($_POST['wc-product-vendor-nonce'], 'save-shop-settings')) { return false; } if (isset($_POST['pv_paypal'])) { if (!is_email($_POST['pv_paypal'])) { wc_add_notice(__('Your PayPal address is not a valid email address.', 'wcvendors'), 'error'); } else { update_user_meta($user_id, 'pv_paypal', $_POST['pv_paypal']); } } if (!empty($_POST['pv_shop_name'])) { $users = get_users(array('meta_key' => 'pv_shop_slug', 'meta_value' => sanitize_title($_POST['pv_shop_name']))); if (!empty($users) && $users[0]->ID != $user_id) { wc_add_notice(__('That shop name is already taken. Your shop name must be unique.', 'wcvendors'), 'error'); } else { update_user_meta($user_id, 'pv_shop_name', $_POST['pv_shop_name']); update_user_meta($user_id, 'pv_shop_slug', sanitize_title($_POST['pv_shop_name'])); } } if (isset($_POST['pv_shop_description'])) { update_user_meta($user_id, 'pv_shop_description', $_POST['pv_shop_description']); } if (isset($_POST['pv_seller_info'])) { update_user_meta($user_id, 'pv_seller_info', $_POST['pv_seller_info']); } do_action('wcvendors_shop_settings_saved', $user_id); if (!wc_notice_count()) { wc_add_notice(__('Settings saved.', 'wcvendors'), 'success'); } } }
/** * Successful Payment! * */ function successful_request($validationResult) { global $woocommerce; $url = get_option('home'); if ($validationResult['payment'] == 'success') { if ($validationResult['auto']) { //in here the order should me marked payd } $order = new WC_Order((int) $validationResult['orderNr']); if ($this->toDec($order->order_key) != $validationResult['stamp']) { exit('key mismatch!'); } if ($order->status != 'completed') { //update the order $order->add_order_note(__('Banklink payment completed', 'woothemes')); $order->payment_complete(); } $url = $this->get_return_url($order); //and always tell the user, that everything is superb.... } else { if ($validationResult['payment'] == 'cancelled') { //in here guide the user nicely to the cart and go out again. $order = new WC_Order((int) $validationResult['orderNr']); if ($this->toDec($order->order_key) != $validationResult['stamp']) { exit('key mismatch!'); } $url = $order->get_cancel_order_url(); } else { //wrong signature, send to front page } } if ($validationResult['auto']) { $url = get_option('home'); } wp_redirect($url); exit; }
/** * Add order note via ajax * * @access public * @return void */ function woocommerce_add_order_note() { global $woocommerce; check_ajax_referer('add-order-note', 'security'); $post_id = (int) $_POST['post_id']; $note = wp_kses_post(trim(stripslashes($_POST['note']))); $note_type = $_POST['note_type']; $is_customer_note = $note_type == 'customer' ? 1 : 0; if ($post_id > 0) { $order = new WC_Order($post_id); $comment_id = $order->add_order_note($note, $is_customer_note); echo '<li rel="' . $comment_id . '" class="note '; if ($is_customer_note) { echo 'customer-note'; } echo '"><div class="note_content">'; echo wpautop(wptexturize($note)); echo '</div><p class="meta"><a href="#" class="delete_note">' . __('Delete note', 'woocommerce') . '</a></p>'; echo '</li>'; } // Quit out die; }
/** * 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; }
public function process_payment($order_id) { global $woocommerce; $wc_order = new WC_Order($order_id); $grand_total = $wc_order->order_total; $amount = (int) $grand_total; include plugin_dir_path(__FILE__) . "lib/Stripe.php"; Stripe::setApiKey($this->stripe_secretkey); Stripe::setApiVersion("2014-06-17"); $token_id = Stripe_Token::create(array("card" => array("number" => $_POST['cardno_stripe'], "exp_month" => $_POST['expmonth_stripe'], "exp_year" => $_POST['expyear_stripe'], "cvc" => $_POST['cardcvv_stripe']))); $charge = Stripe_Charge::create(array("amount" => $amount, "currency" => "USD", "card" => $token_id->id, "metadata" => array("order_id" => $order_id))); if ($token_id->id != '') { if ($charge->paid == true) { $wc_order->add_order_note(__(' Stripe payment completed. ', 'woocommerce')); $wc_order->payment_complete(); return array('result' => 'success', 'redirect' => $this->get_return_url($wc_order)); } else { $wc_order->add_order_note(__('Stripe payment failed. Payment declined.', 'woocommerce')); $woocommerce->add_error(__('Sorry, the transaction was declined.', 'woocommerce')); } } else { $wc_order->add_order_note(__('Stripe payment failed. Payment declined. Please Check your Admin settings', 'woocommerce')); $woocommerce->add_error(__('Sorry, the transaction was declined. Please Check your Admin settings', 'woocommerce')); } }
public function processOrder($order_id) { $order = new WC_Order($order_id); $partsOforderNumber = $this->exploderOrderNumber($order->get_order_number()); $response = $this->prepareResponse(); $this->monetWebPay->log->write("Processing response, payId: " . $response->payId . " dttm: " . $response->dttm . " resultCode: " . $response->resultCode . " resultMessage: " . $response->resultMessage . " authCode: " . $response->authCode . " signature: " . $response->signature); if ($this->monetWebPay->verifyPaymentResponseSignature($response, $this->publicKey, "payment response verify") == false) { $this->monetWebPay->log->write('Response signature verification failed for payId ' . $response->payId); $redirect = $order->get_checkout_payment_url(true); $this->msg['message'] = 'Nepodařilo se ověřit podpis odpovědi'; $this->msg['class'] = 'error'; wc_add_notice(__($this->msg['message'], 'monet') . $error_message, 'error'); return; } if ($response->resultCode != 0) { $this->monetWebPay->log->write('Response resultCode is ' . $response->resultCode . " [" . $response->resultMessage . "] for payId " . $response->payId); } if ($response->paymentStatus == PaymentStatus::$approved) { $this->monetWebPay->log->write('Received approved status for payId: ' . $response->payId); $this->monetWebPay->updateTransactionStatus($partsOforderNumber[0], $response); $this->msg['class'] = 'woocommerce_message'; $this->msg['message'] = sprintf(__('Platba byla zpracována a čeká v bance na zařazení do zúčtovaní. Číslo objednávky: %s', 'monet'), $partsOforderNumber[0]); $order->add_order_note($this->msg['message']); WC()->cart->empty_cart(); $order->payment_complete(); $order->update_status('on-hold'); } else { if ($response->paymentStatus == PaymentStatus::$canceled) { $this->monetWebPay->log->write('Received cancelled status for payId: ' . $response->payId); $this->monetWebPay->clearTransaction($partsOforderNumber[0], $response); $this->msg['message'] = sprintf(__('Platba byla na platební bráně zrušena zákazníkem. Číslo objednávky: %s', 'monet'), $partsOforderNumber[0]); $this->msg['class'] = 'woocommerce_message woocommerce_message_info'; $order->add_order_note($this->msg['message']); $order->update_status('failed'); wc_add_notice(__($this->msg['message'], 'monet') . $error_message, 'error'); } else { if ($response->paymentStatus == PaymentStatus::$declined) { $this->monetWebPay->log->write('Received declined status for payId: ' . $response->payId); $this->monetWebPay->clearTransaction($partsOforderNumber[0], $response); $this->msg['message'] = 'Platba byla na platební bráně zamítnuta. Číslo objednávky: ' . $partsOforderNumber[0]; $this->msg['class'] = 'woocommerce_message woocommerce_message_info'; $order->add_order_note(sprintf($this->msg['message'])); $order->update_status('failed'); wc_add_notice(__($this->msg['message'], 'monet') . $error_message, 'error'); } else { if ($response->paymentStatus == PaymentStatus::$toClearing) { $this->monetWebPay->log->write('Received to_clearing status for payId: ' . $response->payId); $this->monetWebPay->updateTransactionStatus($partsOforderNumber[0], $response); $this->msg['class'] = 'woocommerce_message woocommerce_message_info'; $this->msg['message'] = sprintf(__('Platba byla zpracována a je v bance zařazena do zúčtovaní. Číslo objednavky: %s', 'monet'), $partsOforderNumber[0]); $order->add_order_note($this->msg['message']); WC()->cart->empty_cart(); $order->payment_complete(); } } } } $location = $this->get_return_url($order); wp_safe_redirect($location); exit; }
/** * Checks if the current request is by a user to change the status of their subscription, and if it is * validate the subscription cancellation request and maybe processes the cancellation. * * @since 1.0 */ public static function maybe_change_users_subscription() { global $woocommerce; if (isset($_GET['change_subscription_to']) && isset($_GET['subscription_key']) && isset($_GET['_wpnonce'])) { $user_id = get_current_user_id(); $subscription = self::get_users_subscription($user_id, $_GET['subscription_key']); if (wp_verify_nonce($_GET['_wpnonce'], $_GET['subscription_key']) === false) { $woocommerce->add_error(sprintf(__('That subscription can not be changed to %s. Please contact us if you need assistance.', WC_Subscriptions::$text_domain), $_GET['change_subscription_to'])); } elseif (empty($subscription)) { $woocommerce->add_error(__('That doesn\'t appear to be one of your subscriptions.', WC_Subscriptions::$text_domain)); } elseif (!WC_Subscriptions_Manager::can_subscription_be_changed_to($_GET['change_subscription_to'], $_GET['subscription_key'], $user_id)) { $woocommerce->add_error(sprintf(__('That subscription can not be changed to %s. Please contact us if you need assistance.', WC_Subscriptions::$text_domain), $_GET['change_subscription_to'])); } elseif (!in_array($_GET['change_subscription_to'], array('active', 'on-hold', 'cancelled'))) { $woocommerce->add_error(sprintf(__('Unknown subscription status: "%s". Please contact us if you need assistance.', WC_Subscriptions::$text_domain), $_GET['change_subscription_to'])); } else { switch ($_GET['change_subscription_to']) { case 'active': if (WC_Subscriptions_Manager::subscription_requires_payment($_GET['subscription_key'], $user_id)) { $woocommerce->add_error(sprintf(__('You can not reactive that subscription until paying to renew it. Please contact us if you need assistance.', WC_Subscriptions::$text_domain), $_GET['change_subscription_to'])); } else { self::reactivate_subscription($user_id, $_GET['subscription_key']); $status_message = __('reactivated', WC_Subscriptions::$text_domain); } break; case 'on-hold': if (self::current_user_can_suspend_subscription($_GET['subscription_key'])) { self::put_subscription_on_hold($user_id, $_GET['subscription_key']); $status_message = __('suspended', WC_Subscriptions::$text_domain); } else { $woocommerce->add_error(sprintf(__('You can not suspend that subscription - the suspension limit has been reached. Please contact us if you need assistance.', WC_Subscriptions::$text_domain), $_GET['change_subscription_to'])); } break; case 'cancelled': self::cancel_subscription($user_id, $_GET['subscription_key']); $status_message = __('cancelled', WC_Subscriptions::$text_domain); break; } if (isset($status_message)) { $order = new WC_Order($subscription['order_id']); $order->add_order_note(sprintf(__('The status of subscription %s was changed to %s by the subscriber from their account page.', WC_Subscriptions::$text_domain), $_GET['subscription_key'], $_GET['change_subscription_to'])); $woocommerce->add_message(sprintf(__('Your subscription has been %s.', WC_Subscriptions::$text_domain), $status_message)); } } wp_safe_redirect(get_permalink(woocommerce_get_page_id('myaccount'))); exit; } }
/** * Save the order data meta box. * * @access public * @param mixed $post_id * @param mixed $post * @return void */ function woocommerce_process_shop_order_meta($post_id, $post) { global $wpdb, $woocommerce, $woocommerce_errors; // Add key add_post_meta($post_id, '_order_key', uniqid('order_'), true); // Update post data update_post_meta($post_id, '_billing_first_name', stripslashes($_POST['_billing_first_name'])); update_post_meta($post_id, '_billing_last_name', stripslashes($_POST['_billing_last_name'])); update_post_meta($post_id, '_billing_company', stripslashes($_POST['_billing_company'])); update_post_meta($post_id, '_billing_address_1', stripslashes($_POST['_billing_address_1'])); update_post_meta($post_id, '_billing_address_2', stripslashes($_POST['_billing_address_2'])); update_post_meta($post_id, '_billing_city', stripslashes($_POST['_billing_city'])); update_post_meta($post_id, '_billing_postcode', stripslashes($_POST['_billing_postcode'])); update_post_meta($post_id, '_billing_country', stripslashes($_POST['_billing_country'])); update_post_meta($post_id, '_billing_state', stripslashes($_POST['_billing_state'])); update_post_meta($post_id, '_billing_email', stripslashes($_POST['_billing_email'])); update_post_meta($post_id, '_billing_phone', stripslashes($_POST['_billing_phone'])); update_post_meta($post_id, '_shipping_first_name', stripslashes($_POST['_shipping_first_name'])); update_post_meta($post_id, '_shipping_last_name', stripslashes($_POST['_shipping_last_name'])); update_post_meta($post_id, '_shipping_company', stripslashes($_POST['_shipping_company'])); update_post_meta($post_id, '_shipping_address_1', stripslashes($_POST['_shipping_address_1'])); update_post_meta($post_id, '_shipping_address_2', stripslashes($_POST['_shipping_address_2'])); update_post_meta($post_id, '_shipping_city', stripslashes($_POST['_shipping_city'])); update_post_meta($post_id, '_shipping_postcode', stripslashes($_POST['_shipping_postcode'])); update_post_meta($post_id, '_shipping_country', stripslashes($_POST['_shipping_country'])); update_post_meta($post_id, '_shipping_state', stripslashes($_POST['_shipping_state'])); update_post_meta($post_id, '_order_shipping', stripslashes($_POST['_order_shipping'])); update_post_meta($post_id, '_cart_discount', stripslashes($_POST['_cart_discount'])); update_post_meta($post_id, '_order_discount', stripslashes($_POST['_order_discount'])); update_post_meta($post_id, '_order_total', stripslashes($_POST['_order_total'])); update_post_meta($post_id, '_customer_user', (int) $_POST['customer_user']); update_post_meta($post_id, '_order_tax', stripslashes($_POST['_order_tax'])); update_post_meta($post_id, '_order_shipping_tax', stripslashes($_POST['_order_shipping_tax'])); // Shipping method handling if (get_post_meta($post_id, '_shipping_method', true) !== stripslashes($_POST['_shipping_method'])) { $shipping_method = esc_attr(trim(stripslashes($_POST['_shipping_method']))); update_post_meta($post_id, '_shipping_method', $shipping_method); } if (get_post_meta($post_id, '_shipping_method_title', true) !== stripslashes($_POST['_shipping_method_title'])) { $shipping_method_title = esc_attr(trim(stripslashes($_POST['_shipping_method_title']))); if (!$shipping_method_title) { $shipping_method = esc_attr($_POST['_shipping_method']); $methods = $woocommerce->shipping->load_shipping_methods(); if (isset($methods) && isset($methods[$shipping_method])) { $shipping_method_title = $methods[$shipping_method]->get_title(); } } update_post_meta($post_id, '_shipping_method_title', $shipping_method_title); } // Payment method handling if (get_post_meta($post_id, '_payment_method', true) !== stripslashes($_POST['_payment_method'])) { $methods = $woocommerce->payment_gateways->payment_gateways(); $payment_method = esc_attr($_POST['_payment_method']); $payment_method_title = $payment_method; if (isset($methods) && isset($methods[$payment_method])) { $payment_method_title = $methods[$payment_method]->get_title(); } update_post_meta($post_id, '_payment_method', $payment_method); update_post_meta($post_id, '_payment_method_title', $payment_method_title); } // Update date if (empty($_POST['order_date'])) { $date = current_time('timestamp'); } else { $date = strtotime($_POST['order_date'] . ' ' . (int) $_POST['order_date_hour'] . ':' . (int) $_POST['order_date_minute'] . ':00'); } $wpdb->query($wpdb->prepare("UPDATE {$wpdb->posts} SET post_date = %s WHERE ID = %s", date_i18n('Y-m-d H:i:s', $date), $post_id)); // Tax rows $order_taxes = array(); if (isset($_POST['_order_taxes_label'])) { $order_taxes_label = $_POST['_order_taxes_label']; $order_taxes_compound = isset($_POST['_order_taxes_compound']) ? $_POST['_order_taxes_compound'] : array(); $order_taxes_cart = $_POST['_order_taxes_cart']; $order_taxes_shipping = $_POST['_order_taxes_shipping']; $order_taxes_label_count = sizeof($order_taxes_label); for ($i = 0; $i < $order_taxes_label_count; $i++) { // Add to array if the tax amount is set if (!$order_taxes_cart[$i] && !$order_taxes_shipping[$i]) { continue; } if (!$order_taxes_label[$i]) { $order_taxes_label[$i] = $woocommerce->countries->tax_or_vat(); } if (isset($order_taxes_compound[$i])) { $is_compound = 1; } else { $is_compound = 0; } $order_taxes[] = array('label' => esc_attr($order_taxes_label[$i]), 'compound' => $is_compound, 'cart_tax' => esc_attr($order_taxes_cart[$i]), 'shipping_tax' => esc_attr($order_taxes_shipping[$i])); } } update_post_meta($post_id, '_order_taxes', $order_taxes); // Order items $order_items = array(); if (isset($_POST['item_id'])) { $item_id = $_POST['item_id']; $item_variation = $_POST['item_variation']; $item_name = $_POST['item_name']; $item_quantity = $_POST['item_quantity']; $line_subtotal = $_POST['line_subtotal']; $line_subtotal_tax = $_POST['line_subtotal_tax']; $line_total = $_POST['line_total']; $line_tax = $_POST['line_tax']; $item_meta_names = isset($_POST['meta_name']) ? $_POST['meta_name'] : ''; $item_meta_values = isset($_POST['meta_value']) ? $_POST['meta_value'] : ''; $item_tax_class = $_POST['item_tax_class']; $item_id_count = sizeof($item_id); for ($i = 0; $i < $item_id_count; $i++) { if (!isset($item_id[$i]) || !$item_id[$i]) { continue; } if (!isset($item_name[$i])) { continue; } if (!isset($item_quantity[$i]) || $item_quantity[$i] < 1) { continue; } if (!isset($line_total[$i])) { continue; } if (!isset($line_tax[$i])) { continue; } // Meta $item_meta = new WC_Order_Item_Meta(); if (isset($item_meta_names[$i]) && isset($item_meta_values[$i])) { $meta_names = $item_meta_names[$i]; $meta_values = $item_meta_values[$i]; $meta_names_count = sizeof($meta_names); for ($ii = 0; $ii < $meta_names_count; $ii++) { $meta_name = esc_attr($meta_names[$ii]); $meta_value = esc_attr($meta_values[$ii]); if ($meta_name && $meta_value) { $item_meta->add($meta_name, $meta_value); } } } // Add to array $order_items[] = apply_filters('update_order_item', array('id' => htmlspecialchars(stripslashes($item_id[$i])), 'variation_id' => (int) $item_variation[$i], 'name' => htmlspecialchars(stripslashes($item_name[$i])), 'qty' => (int) $item_quantity[$i], 'line_total' => rtrim(rtrim(number_format(woocommerce_clean($line_total[$i]), 4, '.', ''), '0'), '.'), 'line_tax' => rtrim(rtrim(number_format(woocommerce_clean($line_tax[$i]), 4, '.', ''), '0'), '.'), 'line_subtotal' => rtrim(rtrim(number_format(woocommerce_clean($line_subtotal[$i]), 4, '.', ''), '0'), '.'), 'line_subtotal_tax' => rtrim(rtrim(number_format(woocommerce_clean($line_subtotal_tax[$i]), 4, '.', ''), '0'), '.'), 'item_meta' => $item_meta->meta, 'tax_class' => woocommerce_clean($item_tax_class[$i]))); } } update_post_meta($post_id, '_order_items', $order_items); // Order data saved, now get it so we can manipulate status $order = new WC_Order($post_id); // Order status $order->update_status($_POST['order_status']); // Handle button actions if (isset($_POST['reduce_stock']) && $_POST['reduce_stock'] && sizeof($order_items) > 0) { $order->add_order_note(__('Manually reducing stock.', 'woocommerce')); foreach ($order_items as $order_item) { $_product = $order->get_product_from_item($order_item); if ($_product->exists()) { if ($_product->managing_stock()) { $old_stock = $_product->stock; $new_quantity = $_product->reduce_stock($order_item['qty']); $order->add_order_note(sprintf(__('Item #%s stock reduced from %s to %s.', 'woocommerce'), $order_item['id'], $old_stock, $new_quantity)); $order->send_stock_notifications($_product, $new_quantity, $order_item['qty']); } } else { $order->add_order_note(sprintf(__('Item %s %s not found, skipping.', 'woocommerce'), $order_item['id'], $order_item['name'])); } } $order->add_order_note(__('Manual stock reduction complete.', 'woocommerce')); do_action('woocommerce_reduce_order_stock', $order); } elseif (isset($_POST['restore_stock']) && $_POST['restore_stock'] && sizeof($order_items) > 0) { $order->add_order_note(__('Manually restoring stock.', 'woocommerce')); foreach ($order_items as $order_item) { $_product = $order->get_product_from_item($order_item); if ($_product->exists()) { if ($_product->managing_stock()) { $old_stock = $_product->stock; $new_quantity = $_product->increase_stock($order_item['qty']); $order->add_order_note(sprintf(__('Item #%s stock increased from %s to %s.', 'woocommerce'), $order_item['id'], $old_stock, $new_quantity)); } } else { $order->add_order_note(sprintf(__('Item %s %s not found, skipping.', 'woocommerce'), $order_item['id'], $order_item['name'])); } } $order->add_order_note(__('Manual stock restore complete.', 'woocommerce')); do_action('woocommerce_restore_order_stock', $order); } elseif (isset($_POST['invoice']) && $_POST['invoice']) { do_action('woocommerce_before_send_customer_invoice', $order); $mailer = $woocommerce->mailer(); $mailer->customer_invoice($order); do_action('woocommerce_after__customer_invoice', $order); } delete_transient('woocommerce_processing_order_count'); }
function inicis_escrow_request_denyconfirm($posted) { global $inicis_payment; if (empty($_POST['dcnf_name']) && empty($_POST['tid']) && empty($_POST['mid'])) { return false; } require $inicis_payment->plugin_path() . "/lib/inipay50/INILib.php"; $iniescrow = new INIpay50(); $iniescrow->SetField("inipayhome", $this->settings['libfolder']); // 이니페이 홈디렉터리(상점수정 필요) $iniescrow->SetField("tid", $_POST['tid']); // 거래아이디 $iniescrow->SetField("mid", $_POST['mid']); // 상점아이디 $iniescrow->SetField("admin", "1111"); // 키패스워드(상점아이디에 따라 변경) $iniescrow->SetField("type", "escrow"); // 고정 (절대 수정 불가) $iniescrow->SetField("escrowtype", "dcnf"); // 고정 (절대 수정 불가) $iniescrow->SetField("dcnf_name", $_POST['dcnf_name']); $iniescrow->SetField("debug", "true"); // 로그모드("true"로 설정하면 상세한 로그가 생성됨) $iniescrow->startAction(); $tid = $iniescrow->GetResult("tid"); // 거래번호 $resultCode = $iniescrow->GetResult("ResultCode"); // 결과코드 ("00"이면 지불 성공) $resultMsg = $iniescrow->GetResult("ResultMsg"); // 결과내용 (지불결과에 대한 설명) $resultDate = $iniescrow->GetResult("DCNF_Date"); // 처리 날짜 $resultTime = $iniescrow->GetResult("DCNF_Time"); // 처리 시각 $postid = $_POST['postid']; $orderinfo = new WC_Order($_POST['postid']); if ($resultCode == '00') { $tmp_settings = get_option('woocommerce_' . $this->id . '_settings', TRUE); $refunded_status = $tmp_settings['order_status_after_refund']; $orderinfo->update_status($refunded_status); //취소처리완료 상태로 변경 update_post_meta($_POST['post_id'], '`_inicis_escrow_order_cancelled`', TRUE); $orderinfo->add_order_note(sprintf(__('에스크로 구매거절을 %s님께서 <font color=blue><strong>확인</strong></font>하였습니다. 에스크로 환불처리 완료하였습니다. 거래번호 : %s, 결과코드 : %s, 처리날짜 : %s, 처리시각 : %s', 'inicis_payment'), $_POST['dcnf_name'], $_POST['tid'], $resultCode, $resultDate, $resultTime)); } else { $orderinfo->add_order_note(sprintf(__('에스크로 구매거절을 %s님께서 <font color=blue><strong>확인실패</strong></font>하였습니다. 에스크로 환불처리를 실패하였습니다. 에러메시지를 확인하세요! 거래번호 : %s, 결과코드 : %s, 에러메시지 : %s, 처리날짜 : %s, 처리시각 : %s', 'inicis_payment'), $_POST['dcnf_name'], $_POST['tid'], $resultCode, mb_convert_encoding($resultMsg, "UTF-8", "EUC-KR"), $resultDate, $resultTime)); die; } }