function process_payment($order_id)
 {
     global $woocommerce;
     $order = new woocommerce_order($order_id);
     $order->update_status('on-hold', __('Payment to be made upon delivery.', 'woocommerce'));
     $woocommerce->cart->empty_cart();
     // Dump the cart
     unset($_SESSION['order_awaiting_payment']);
     // Lose our session
     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')))));
 }
        /**
         * Generate paytm button link
         **/
        public function generate_paytm_form($order_id)
        {
            global $woocommerce;
            $txnDate = date('Y-m-d');
            $milliseconds = (int) (1000 * strtotime(date('Y-m-d')));
            if (version_compare(WOOCOMMERCE_VERSION, '2.0.0', '>=')) {
                $order = new WC_Order($order_id);
            } else {
                $order = new woocommerce_order($order_id);
            }
            $redirect_url = $this->redirect_page_id == "" || $this->redirect_page_id == 0 ? get_site_url() . "/" : get_permalink($this->redirect_page_id);
            // pretty url check //
            $a = strstr($redirect_url, "?");
            if ($a) {
                $redirect_url .= "&wc-api=WC_paytm";
            } else {
                $redirect_url .= "?wc-api=WC_paytm";
            }
            error_log("redirect url = this {$redirect_url}");
            //////////////
            $order_id = $order_id;
            $amt = $order->order_total;
            $txntype = '1';
            $ptmoption = '1';
            $currency = "INR";
            $purpose = "1";
            $productDescription = 'paytm';
            $ip = $_SERVER['REMOTE_ADDR'];
            /*$post_variables = Array(
            			"merchantIdentifier" => $this -> merchantIdentifier,
            			"orderId" => $order_id,
            			"returnUrl" => $redirect_url,
            			"buyerEmail" => $order -> billing_email,
            			"buyerFirstName" => $order -> billing_first_name,
            			"buyerLastName" => $order -> billing_last_name,
            			"buyerAddress" => $order -> billing_address_1,
            			"buyerCity" => $order -> billing_city,
            			"buyerState" => $order -> billing_state,
            			"buyerCountry" => $order -> billing_country,
            			"buyerPincode" => $order -> billing_postcode,
            			"buyerPhoneNumber" => $order -> billing_phone,
            			"txnType" => $txntype,
            			"ptmoption" => $ptmoption,
            			"mode" => $this -> mode,
            			"currency" => $currency,
            			"amount" => $amt, //Amount should be in paisa
            			"merchantIpAddress" => $ip,
            			"purpose" => $purpose,
            			"productDescription" => $productDescription,
            			"txnDate" => $txnDate
            
            			);*/
            $email = '';
            $mobile_no = '';
            try {
                $email = $order->billing_email;
            } catch (Exception $e) {
            }
            try {
                $mobile_no = preg_replace('#[^0-9]{0,13}#is', '', $order->billing_phone);
            } catch (Exception $e) {
            }
            $post_variables = array("MID" => $this->merchantIdentifier, "ORDER_ID" => $order_id, "CUST_ID" => $order->billing_first_name, "TXN_AMOUNT" => $amt, "CHANNEL_ID" => $this->channel_id, "INDUSTRY_TYPE_ID" => $this->industry_type, "WEBSITE" => $this->website, "EMAIL" => $email, "MOBILE_NO" => $mobile_no);
            if ($this->callbackurl == 'yes') {
                $post_variables["CALLBACK_URL"] = get_site_url() . '/?page_id=7&wc-api=WC_paytm';
            }
            $all = '';
            foreach ($post_variables as $name => $value) {
                if ($name != 'checksum') {
                    $all .= "'";
                    if ($name == 'returnUrl') {
                        $all .= $value;
                    } else {
                        $all .= $value;
                    }
                    $all .= "'";
                }
            }
            if ($this->log == "yes") {
                error_log("AllParams : " . $all);
                error_log("Secret Key : " . $this->secret_key);
            }
            //$checksum = Checksum::calculateChecksum($this->secret_key, $all);
            $checksum = getChecksumFromArray($post_variables, $this->secret_key);
            $paytm_args = array('merchantIdentifier' => $this->merchantIdentifier, 'orderId' => $order_id, 'returnUrl' => $redirect_url, 'buyerEmail' => $order->billing_email, 'buyerFirstName' => $order->billing_first_name, 'buyerLastName' => $order->billing_last_name, 'buyerAddress' => $order->billing_address_1, 'buyerCity' => $order->billing_city, 'buyerState' => $order->billing_state, 'buyerCountry' => $order->billing_country, 'buyerPincode' => $order->billing_postcode, 'buyerPhoneNumber' => $order->billing_phone, 'txnType' => $txntype, 'ptmoption' => $ptmoption, 'mode' => $this->mode, 'currency' => $currency, 'amount' => $amt, 'merchantIpAddress' => $ip, 'purpose' => $purpose, 'productDescription' => $productDescription, 'txnDate' => $txnDate, 'checksum' => $checksum);
            foreach ($paytm_args as $name => $value) {
                if ($name != 'checksum') {
                    if ($name == 'returnUrl') {
                        $value = $value;
                    } else {
                        $value = $value;
                    }
                }
            }
            $paytm_args_array = array();
            /* foreach($paytm_args as $key => $value){
            						if($key != 'checksum') {
            			if ($key == 'returnUrl') {
                            $paytm_args_array[] = "<input type='hidden' name='$key' value='". $value ."'/>";
            				} else {
            				$paytm_args_array[] = "<input type='hidden' name='$key' value='". $value ."'/>";
            				}
            				} else {
            				$paytm_args_array[] = "<input type='hidden' name='$key' value='$value'/>";
            				}
                        }*/
            $paytm_args_array[] = "<input type='hidden' name='MID' value='" . $this->merchantIdentifier . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='ORDER_ID' value='" . $order_id . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='WEBSITE' value='" . $this->website . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='INDUSTRY_TYPE_ID' value='" . $this->industry_type . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='CHANNEL_ID' value='" . $this->channel_id . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='TXN_AMOUNT' value='" . $amt . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='CUST_ID' value='" . $order->billing_first_name . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='EMAIL' value='" . $email . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='MOBILE_NO' value='" . $mobile_no . "'/>";
            if ($this->callbackurl == 'yes') {
                $call = get_site_url() . '/?page_id=7&wc-api=WC_paytm';
                $paytm_args_array[] = "<input type='hidden' name='CALLBACK_URL' value='" . $call . "'/>";
            }
            $paytm_args_array[] = "<input type='hidden' name='txnDate' value='" . date('Y-m-d H:i:s') . "'/>";
            $paytm_args_array[] = "<input type='hidden' name='CHECKSUMHASH' value='" . $checksum . "'/>";
            return '<form action="' . $this->gateway_url . '" method="post" id="paytm_payment_form">
                ' . implode('', $paytm_args_array) . '
                <input type="submit" class="button-alt" id="submit_paytm_payment_form" value="' . __('Pay via paytm') . '" /> <a class="button cancel" href="' . $order->get_cancel_order_url() . '">' . __('Cancel order &amp; restore cart') . '</a>
                <script type="text/javascript">
jQuery(function(){
    jQuery("body").block(
            {
                message: "<img src=\\"' . $woocommerce->plugin_url() . '/assets/images/ajax-loader.gif\\" alt=\\"Redirecting…\\" style=\\"float:left; margin-right: 10px;\\" />' . __('Thank you for your order. We are now redirecting you to paytm to make payment.') . '",
                    overlayCSS:
            {
                background: "#fff",
                    opacity: 0.6
        },
        css: {
            padding:        20,
                textAlign:      "center",
                color:          "#555",
                border:         "3px solid #aaa",
                backgroundColor:"#fff",
                cursor:         "wait",
                lineHeight:"32px"
        }
        });
        jQuery("#submit_paytm_payment_form").click();

        });
                    </script>
                </form>';
        }
 /**
  * Successful Payment!
  **/
 function successful_request($posted)
 {
     // Custom holds post ID
     if (!empty($posted['custom']) && !empty($posted['invoice'])) {
         $order = new woocommerce_order((int) $posted['custom']);
         if ($order->order_key !== $posted['invoice']) {
             exit;
         }
         // Sandbox fix
         if ($posted['test_ipn'] == 1 && $posted['payment_status'] == 'Pending') {
             $posted['payment_status'] = 'completed';
         }
         // We are here so lets check status and do actions
         switch (strtolower($posted['payment_status'])) {
             case 'completed':
                 // Check order not already completed
                 if ($order->status == 'completed') {
                     exit;
                 }
                 // Check valid txn_type
                 $accepted_types = array('cart', 'instant', 'express_checkout', 'web_accept', 'masspay', 'send_money');
                 if (!in_array(strtolower($posted['txn_type']), $accepted_types)) {
                     exit;
                 }
                 // Payment completed
                 $order->add_order_note(__('IPN payment completed', 'woothemes'));
                 $order->payment_complete();
                 // Store PP Details
                 update_post_meta((int) $posted['custom'], 'Payer PayPal address', $posted['payer_email']);
                 update_post_meta((int) $posted['custom'], 'Transaction ID', $posted['txn_id']);
                 update_post_meta((int) $posted['custom'], 'Payer first name', $posted['first_name']);
                 update_post_meta((int) $posted['custom'], 'Payer last name', $posted['last_name']);
                 update_post_meta((int) $posted['custom'], 'Payment type', $posted['payment_type']);
                 break;
             case 'denied':
             case 'expired':
             case 'failed':
             case 'voided':
                 // Order failed
                 $order->update_status('failed', sprintf(__('Payment %s via IPN.', 'woothemes'), strtolower($posted['payment_status'])));
                 break;
             case "refunded":
             case "reversed":
             case "chargeback":
                 // Mark order as refunded
                 $order->update_status('refunded', sprintf(__('Payment %s via IPN.', 'woothemes'), strtolower($posted['payment_status'])));
                 $message = woocommerce_mail_template(__('Order refunded/reversed', 'woothemes'), sprintf(__('Order #%s has been marked as refunded - PayPal reason code: %s', 'woothemes'), $order->id, $posted['reason_code']));
                 // Send the mail
                 woocommerce_mail(get_option('woocommerce_new_order_email_recipient'), sprintf(__('Payment for order #%s refunded/reversed', 'woothemes'), $order->id), $message);
                 break;
             default:
                 // No action
                 break;
         }
         exit;
     }
 }
/**
 * Outputs the pay page - payment gateways can hook in here to show payment forms etc
 **/
function woocommerce_pay()
{
    global $woocommerce, $order;
    if (isset($_GET['pay_for_order']) && isset($_GET['order']) && isset($_GET['order_id'])) {
        // Pay for existing order
        $order_key = urldecode($_GET['order']);
        $order_id = (int) $_GET['order_id'];
        $order = new woocommerce_order($order_id);
        if ($order->id == $order_id && $order->order_key == $order_key && in_array($order->status, array('pending', 'failed'))) {
            // Set customer location to order location
            if ($order->billing_country) {
                $woocommerce->customer->set_country($order->billing_country);
            }
            if ($order->billing_state) {
                $woocommerce->customer->set_state($order->billing_state);
            }
            if ($order->billing_postcode) {
                $woocommerce->customer->set_postcode($order->billing_postcode);
            }
            // Pay form was posted - process payment
            if (isset($_POST['pay']) && $woocommerce->verify_nonce('pay')) {
                // Update payment method
                if ($order->order_total > 0) {
                    $payment_method = woocommerce_clean($_POST['payment_method']);
                    $available_gateways = $woocommerce->payment_gateways->get_available_payment_gateways();
                    // Update meta
                    update_post_meta($order_id, '_payment_method', $payment_method);
                    if (isset($available_gateways) && isset($available_gateways[$payment_method])) {
                        $payment_method_title = $available_gateways[$payment_method]->title;
                    }
                    update_post_meta($order_id, '_payment_method_title', $payment_method_title);
                    $result = $available_gateways[$payment_method]->process_payment($order_id);
                    // Redirect to success/confirmation/payment page
                    if ($result['result'] == 'success') {
                        wp_redirect($result['redirect']);
                        exit;
                    }
                } else {
                    // No payment was required for order
                    $order->payment_complete();
                    wp_safe_redirect(get_permalink(get_option('woocommerce_thanks_page_id')));
                    exit;
                }
            }
            // Show form
            woocommerce_get_template('checkout/pay_for_order.php');
        } elseif (!in_array($order->status, array('pending', 'failed'))) {
            $woocommerce->add_error(__('Your order has already been paid for. Please contact us if you need assistance.', 'woothemes'));
            $woocommerce->show_messages();
        } else {
            $woocommerce->add_error(__('Invalid order.', 'woothemes'));
            $woocommerce->show_messages();
        }
    } else {
        // Pay for order after checkout step
        if (isset($_GET['order'])) {
            $order_id = $_GET['order'];
        } else {
            $order_id = 0;
        }
        if (isset($_GET['key'])) {
            $order_key = $_GET['key'];
        } else {
            $order_key = '';
        }
        if ($order_id > 0) {
            $order = new woocommerce_order($order_id);
            if ($order->order_key == $order_key && in_array($order->status, array('pending', 'failed'))) {
                ?>
				<ul class="order_details">
					<li class="order">
						<?php 
                _e('Order:', 'woothemes');
                ?>
						<strong># <?php 
                echo $order->id;
                ?>
</strong>
					</li>
					<li class="date">
						<?php 
                _e('Date:', 'woothemes');
                ?>
						<strong><?php 
                echo date(get_option('date_format'), strtotime($order->order_date));
                ?>
</strong>
					</li>
					<li class="total">
						<?php 
                _e('Total:', 'woothemes');
                ?>
						<strong><?php 
                echo woocommerce_price($order->order_total);
                ?>
</strong>
					</li>
					<li class="method">
						<?php 
                _e('Payment method:', 'woothemes');
                ?>
						<strong><?php 
                echo $order->payment_method_title;
                ?>
</strong>
					</li>
				</ul>
				
				<?php 
                do_action('woocommerce_receipt_' . $order->payment_method, $order_id);
                ?>
				
				<div class="clear"></div>
				<?php 
            } else {
                wp_safe_redirect(get_permalink(get_option('woocommerce_myaccount_page_id')));
                exit;
            }
        } else {
            wp_safe_redirect(get_permalink(get_option('woocommerce_myaccount_page_id')));
            exit;
        }
    }
}