/**
  * This function handles the processing of the payments - it should be overrideen in child classes
  * @param string $args The args for the fucnction
  * @since 3.0
  */
 function process_payment(){
   global $wpi_settings, $invoice;
   /** Pull the invoice */
   $the_invoice = new WPI_Invoice();
   $invoice = $the_invoice->load_invoice("return=true&id=".wpi_invoice_id_to_post_id($_REQUEST['invoice_id']));
   /** Call the child function based on the wpi_type variable sent */
   $wpi_settings['installed_gateways'][$_REQUEST['type']]['object']->process_payment();
   die();
 }
Esempio n. 2
0
 /**
  * Handler for PayPal IPN queries
  * @author korotkov@ud
  * Full callback URL: http://domain/wp-admin/admin-ajax.php?action=wpi_gateway_server_callback&type=wpi_paypal
  */
 static function server_callback()
 {
     if (empty($_POST)) {
         die(__('Direct access not allowed', WPI));
     }
     $invoice = new WPI_Invoice();
     $invoice->load_invoice("id={$_POST['invoice']}");
     /** Verify callback request */
     if (self::_ipn_verified($invoice)) {
         switch ($_POST['txn_type']) {
             /** New PayPal Subscription */
             case 'subscr_signup':
                 /** PayPal Subscription created */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription created', WPI));
                 wp_invoice_mark_as_pending($_POST['invoice']);
                 do_action('wpi_paypal_subscr_signup_ipn', $_POST);
                 break;
             case 'subscr_cancel':
                 /** PayPal Subscription cancelled */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription cancelled', WPI));
                 do_action('wpi_paypal_subscr_cancel_ipn', $_POST);
                 break;
             case 'subscr_failed':
                 /** PayPal Subscription failed */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription payment failed', WPI));
                 do_action('wpi_paypal_subscr_failed_ipn', $_POST);
                 break;
             case 'subscr_payment':
                 /** Payment of Subscription */
                 switch ($_POST['payment_status']) {
                     case 'Completed':
                         /** Add payment amount */
                         $event_note = sprintf(__('%1s paid for subscription %2s', WPI), WPI_Functions::currency_format(abs($_POST['mc_gross']), $_POST['invoice']), $_POST['subscr_id']);
                         $event_amount = (double) $_POST['mc_gross'];
                         $event_type = 'add_payment';
                         /** Log balance changes */
                         $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                         $invoice->save_invoice();
                         send_notification($invoice->data);
                         break;
                     default:
                         break;
                 }
                 do_action('wpi_paypal_subscr_payment_ipn', $_POST);
                 break;
             case 'subscr_eot':
                 /** PayPal Subscription end of term */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription term is finished', WPI));
                 wp_invoice_mark_as_paid($_POST['invoice'], $check = false);
                 do_action('wpi_paypal_subscr_eot_ipn', $_POST);
                 break;
             case 'subscr_modify':
                 /** PayPal Subscription modified */
                 WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['invoice']), 'invoice', 'update', '', __('PayPal Subscription modified', WPI));
                 do_action('wpi_paypal_subscr_modify_ipn', $_POST);
                 break;
             case 'web_accept':
                 /** PayPal simple button */
                 switch ($_POST['payment_status']) {
                     case 'Pending':
                         /** Mark invoice as Pending */
                         wp_invoice_mark_as_pending($_POST['invoice']);
                         do_action('wpi_paypal_pending_ipn', $_POST);
                         break;
                     case 'Completed':
                         /** Add payment amount */
                         $event_note = sprintf(__('%s paid via PayPal', WPI), WPI_Functions::currency_format(abs($_POST['mc_gross']), $_POST['invoice']));
                         $event_amount = (double) $_POST['mc_gross'];
                         $event_type = 'add_payment';
                         /** Log balance changes */
                         $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                         /** Log payer email */
                         $payer_email = sprintf(__("PayPal Payer email: %s", WPI), $_POST['payer_email']);
                         $invoice->add_entry("attribute=invoice&note={$payer_email}&type=update");
                         $invoice->save_invoice();
                         /** ... and mark invoice as paid */
                         wp_invoice_mark_as_paid($_POST['invoice'], $check = true);
                         send_notification($invoice->data);
                         do_action('wpi_paypal_complete_ipn', $_POST);
                         break;
                     default:
                         break;
                 }
                 break;
             case 'cart':
                 /** PayPal Cart. Used for SPC */
                 switch ($_POST['payment_status']) {
                     case 'Pending':
                         /** Mark invoice as Pending */
                         wp_invoice_mark_as_pending($_POST['invoice']);
                         do_action('wpi_paypal_pending_ipn', $_POST);
                         break;
                     case 'Completed':
                         /** Add payment amount */
                         $event_note = sprintf(__('%s paid via PayPal', WPI), WPI_Functions::currency_format(abs($_POST['mc_gross']), $_POST['invoice']));
                         $event_amount = (double) $_POST['mc_gross'];
                         $event_type = 'add_payment';
                         /** Log balance changes */
                         $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                         /** Log payer email */
                         $payer_email = sprintf(__("PayPal Payer email: %s", WPI), $_POST['payer_email']);
                         $invoice->add_entry("attribute=invoice&note={$payer_email}&type=update");
                         $invoice->save_invoice();
                         /** ... and mark invoice as paid */
                         wp_invoice_mark_as_paid($_POST['invoice'], $check = true);
                         send_notification($invoice->data);
                         do_action('wpi_paypal_complete_ipn', $_POST);
                         break;
                     default:
                         break;
                 }
                 break;
             default:
                 break;
         }
         echo ' ';
     }
 }
  /**
   * Add itemized charge like itemized list item
   *
   * @param int $invoice_id
   * @param string $name
   * @param float $amount
   * @param float $tax
   * @return array
   */
  function add_itemized_charge($invoice_id, $name, $amount, $tax) {

    $post_id = wpi_invoice_id_to_post_id($invoice_id);
    $charge_items = get_post_meta($post_id, 'itemized_charges', true);

    $new_item = array(
        'name' => $name,
        'amount' => $amount,
        'tax' => $tax,
        'before_tax' => $amount,
        'after_tax' => $amount + ($amount / 100 * $tax)
    );

    if (!empty($charge_items)) {
      $charge_items[] = $new_item;
    } else {
      $charge_items[0] = $new_item;
    }

    update_post_meta($post_id, 'itemized_charges', $charge_items);

    return end($charge_items);
  }
Esempio n. 4
0
 /**
  * Handles validation when somebody is attempting to view an invoice.
  * If validation is passsed, we add the necessary
  * filters to display the invoice header and page content;
  * Global $invoice_id variable set by WPI_Functions::validate_page_hash();
  */
 function template_redirect()
 {
     global $invoice_id, $wpi_settings, $wpi_invoice_object, $post, $current_user;
     //** Alwys load styles without checking if given page has an invoice */
     wp_enqueue_style('wpi-theme-specific');
     wp_enqueue_style('wpi-default-style');
     //** Determine if the current page is invoice's page */
     if (empty($post->ID) || $wpi_settings['web_invoice_page'] != $post->ID) {
         return;
     }
     //** If invoice_id is passed, run validate_page_hash  to make sure this is the right page and invoice_id exists */
     if (isset($_GET['invoice_id'])) {
         if (WPI_Functions::validate_page_hash(esc_sql($_GET['invoice_id']))) {
             //** load global invoice object */
             $post_id = wpi_invoice_id_to_post_id($invoice_id);
             $wpi_invoice_object = new WPI_Invoice();
             $wpi_invoice_object->load_invoice("id={$post_id}");
             add_filter('viewable_invoice_types', array($this, 'viewable_types'));
             //** Determine if current invoice object is "viewable" */
             if (!in_array($wpi_invoice_object->data['post_status'], apply_filters('viewable_invoice_types', array('active')))) {
                 return;
             }
             if (isset($wpi_settings['logged_in_only']) && $wpi_settings['logged_in_only'] == 'true') {
                 if (!current_user_can(WPI_UI::get_capability_by_level($wpi_settings['user_level'])) && !WPI_Functions::user_is_invoice_recipient($wpi_invoice_object)) {
                     //** Show 404 when invoice doesn't exist */
                     $not_found = get_query_template('404');
                     require_once $not_found;
                     die;
                 }
             }
             //** Load front end scripts */
             wp_enqueue_script('jquery.validate');
             wp_enqueue_script('wpi-gateways');
             wp_enqueue_script('jquery.maskedinput');
             wp_enqueue_script('wpi-frontend-scripts');
             if (!empty($wpi_settings['ga_event_tracking']) && $wpi_settings['ga_event_tracking']['enabled'] == 'true') {
                 wp_enqueue_script('wpi-ga-tracking', WPI_URL . "/core/js/wpi.ga.tracking.js", array('jquery'));
             }
             //** Apply Filters to the invoice description */
             add_action('wpi_description', 'wpautop');
             add_action('wpi_description', 'wptexturize');
             add_action('wpi_description', 'shortcode_unautop');
             add_action('wpi_description', 'convert_chars');
             add_action('wpi_description', 'capital_P_dangit');
             //** Declare the variable that will hold our AJAX url for JavaScript purposes */
             wp_localize_script('wpi-gateways', 'wpi_ajax', array('url' => admin_url('admin-ajax.php')));
             add_action('wp_head', array('WPI_UI', 'frontend_header'));
             if ($wpi_settings['replace_page_title_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
                 add_action('wp_title', array('WPI_UI', 'wp_title'), 0, 3);
             }
             if ($wpi_settings['replace_page_heading_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
                 add_action('the_title', array('WPI_UI', 'the_title'), 0, 2);
             }
             add_action('the_content', array('WPI_UI', 'the_content'), 20);
         } else {
             //** Show 404 when invoice doesn't exist */
             $not_found = get_query_template('404');
             require_once $not_found;
             die;
         }
     }
     //** Fixed WordPress filters if page is being opened in HTTPS mode */
     if (isset($_SERVER['HTTPS']) && $_SERVER["HTTPS"] == "on") {
         if (function_exists('force_ssl')) {
             add_filter('option_siteurl', 'force_ssl');
             add_filter('option_home', 'force_ssl');
             add_filter('option_url', 'force_ssl');
             add_filter('option_wpurl', 'force_ssl');
             add_filter('option_stylesheet_url', 'force_ssl');
             add_filter('option_template_url', 'force_ssl');
             add_filter('script_loader_src', 'force_ssl');
         }
     }
     //** Lookup functionality */
     if (isset($_POST['wp_invoice_lookup_input'])) {
         if (!empty($current_user->ID)) {
             $id = get_invoice_id($_POST['wp_invoice_lookup_input']);
             if (empty($id)) {
                 //** Show 404 when invoice doesn't exist */
                 $not_found = get_query_template('404');
                 require_once $not_found;
                 die;
             }
             $invoice = get_invoice($id);
             if (current_user_can('level_10') || $current_user->data->user_email == $invoice['user_email']) {
                 header("location:" . get_invoice_permalink($_POST['wp_invoice_lookup_input']));
                 die;
             } else {
                 //** Show 404 when invoice doesn't exist */
                 $not_found = get_query_template('404');
                 require_once $not_found;
                 die;
             }
         } else {
             //** Show 404 when invoice doesn't exist */
             $not_found = get_query_template('404');
             require_once $not_found;
             die;
         }
     }
 }
Esempio n. 5
0
 /**
  * Handler for Silent Post Url
  */
 static function server_callback()
 {
     $arb = false;
     $fields = array();
     foreach ($_REQUEST as $name => $value) {
         $fields[$name] = $value;
         if ($name == 'x_subscription_id') {
             $arb = true;
         }
     }
     // Handle recurring billing payments
     if ($arb == true && $fields['x_response_code'] == 1) {
         $paynum = $fields['x_subscription_paynum'];
         $subscription_id = $fields['x_subscription_id'];
         $amount = $fields['x_amount'];
         $invoice_id = wpi_post_id_to_invoice_id(wpi_subscription_id_to_post_id($subscription_id));
         $invoice_obj = new WPI_Invoice();
         $invoice_obj->load_invoice("id={$invoice_id}");
         // Add payment amount
         $event_note = WPI_Functions::currency_format(abs($amount), $invoice_id) . ". ARB payment {$paynum} of {$invoice_obj->data['recurring']['wpi_authorize']['cycles']}";
         $event_amount = $amount;
         $event_type = 'add_payment';
         $invoice_obj->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
         // Complete subscription if last payment done
         if ($invoice_obj->data['recurring']['wpi_authorize']['cycles'] <= $paynum) {
             WPI_Functions::log_event(wpi_invoice_id_to_post_id($invoice_id), 'invoice', 'update', '', __('Subscription completely paid', WPI));
             wp_invoice_mark_as_paid($invoice_id);
         }
         $invoice_obj->save_invoice();
     }
 }
 function show_invoice_charges() {
   $invoice_id = intval($_REQUEST['invoice_id']);
   WPI_Functions::get_charges(wpi_invoice_id_to_post_id($invoice_id));
   die();
 }
Esempio n. 7
0
 /**
  * Calculate amounts on each update
  *
  * @global type $wpdb
  * @global type $blog_id
  */
 function calculate_totals()
 {
     global $wpdb, $blog_id;
     //** Flush vars */
     $taxable_subtotal = 0;
     $non_taxable_subtotal = 0;
     $tax_percents = array();
     $total_charges = 0;
     $total = 0;
     $this->data['subtotal'] = 0;
     $this->data['total_tax'] = 0;
     $this->data['total_discount'] = 0;
     //** Services itemized list */
     if (isset($this->data['itemized_list']) && is_array($this->data['itemized_list'])) {
         foreach ($this->data['itemized_list'] as $key => $value) {
             if ($value['line_total_tax'] > 0) {
                 $taxable_subtotal += $value['line_total_before_tax'];
                 $tax_percents[] = array('tax' => $value['tax_rate'], 'qty' => $value['quantity'], 'prc' => $value['price']);
             } else {
                 $non_taxable_subtotal += $value['line_total_before_tax'];
             }
         }
     }
     //** The same is for Charges itemized list */
     if (!empty($this->data['itemized_charges']) && is_array($this->data['itemized_charges'])) {
         foreach ($this->data['itemized_charges'] as $key => $value) {
             if (!empty($value['tax_amount']) && $value['tax_amount'] > 0) {
                 $taxable_subtotal += $value['amount'];
                 $tax_percents[] = array('tax' => $value['tax'], 'qty' => 1, 'prc' => $value['amount']);
                 $total_charges += $value['amount'];
             } else {
                 $non_taxable_subtotal += $value['amount'];
             }
         }
     }
     $avg_tax = 0;
     $sum = 0;
     if (!empty($tax_percents)) {
         foreach ($tax_percents as $tax_item) {
             $sum += $tax_item['tax'];
         }
         $avg_tax = $sum / count($tax_percents);
     }
     $this->data['subtotal'] = $taxable_subtotal + $non_taxable_subtotal;
     //** Get discount */
     if (!empty($this->data['discount']) && is_array($this->data['discount'])) {
         $highest_percent = 0;
         foreach ($this->data['discount'] as $key => $value) {
             if ($value['type'] == 'percent') {
                 //** if a percentage is found, we make a note of it, and build a percentage array, which will later be used to calculate the highest */
                 $percentage_found = true;
                 if ((int) $highest_percent < (int) $value['amount']) {
                     $highest_percent = $value['amount'];
                 }
             } else {
                 //** if non percentage, simply calculate the sum of all the discounts */
                 $this->data['total_discount'] = $this->data['total_discount'] + $value['amount'];
             }
         }
         if (isset($percentage_found) && $percentage_found == true) {
             //** Only do this if a percentage was found.  figure out highest percentage, and overwrite total_discount */
             $this->data['total_discount'] = $this->data['subtotal'] * ($highest_percent / 100);
         }
     }
     //** Handle Tax Method */
     if (!empty($this->data['tax_method'])) {
         switch ($this->data['tax_method']) {
             case 'before_discount':
                 foreach ($tax_percents as $tax_item) {
                     $this->data['total_tax'] += $tax_item['prc'] / 100 * $tax_item['tax'] * $tax_item['qty'];
                 }
                 break;
             case 'after_discount':
                 $subtotal_with_discount = $this->data['subtotal'] - $this->data['total_discount'];
                 if ($this->data['subtotal'] > 0) {
                     $taxable_amount = $taxable_subtotal / $this->data['subtotal'] * $subtotal_with_discount;
                 } else {
                     $taxable_amount = 0;
                 }
                 $this->data['total_tax'] = $taxable_amount * $avg_tax / 100;
                 break;
             default:
                 foreach ($tax_percents as $tax_item) {
                     $this->data['total_tax'] += $tax_item['prc'] / 100 * $tax_item['tax'] * $tax_item['qty'];
                 }
                 break;
         }
     } else {
         $this->data['tax_method'] = 'before_discount';
         foreach ($tax_percents as $tax_item) {
             $this->data['total_tax'] += $tax_item['prc'] / 100 * $tax_item['tax'] * $tax_item['qty'];
         }
     }
     $total = number_format((double) ($this->data['subtotal'] - $this->data['total_discount'] + $this->data['total_tax']), 2, '.', '');
     $total_payments = 0;
     $total_admin_adjustment = 0;
     $refunds = 0;
     $invoice_id = $this->data['invoice_id'];
     //** Add support for MS and for old invoice histories which will have a blog_id of 0 after upgrade */
     if ($blog_id == 1) {
         $ms_blog_query = " AND ( blog_id = {$blog_id} OR blog_id = 0 ) ";
     } else {
         $ms_blog_query = " AND blog_id = {$blog_id} ";
     }
     $this->data['log'] = $wpdb->get_results("SELECT * FROM {$wpdb->base_prefix}wpi_object_log WHERE object_id = '" . wpi_invoice_id_to_post_id($invoice_id) . "' {$ms_blog_query}  ", ARRAY_A);
     //** Calculate adjustments and refunds */
     if (is_array($this->data['log'])) {
         //** Loop log items */
         foreach ($this->data['log'] as $log_event) {
             //** If log item is add_payment */
             if ($log_event['action'] == 'add_payment') {
                 $total_payments += $log_event['value'];
             }
             //** If log item is do_adjustment */
             if ($log_event['action'] == 'do_adjustment') {
                 $total_admin_adjustment += $log_event['value'];
             }
             //** If log item is refund */
             if ($log_event['action'] == 'refund') {
                 $refunds += $log_event['value'];
             }
         }
     }
     $this->data['total_payments'] = $total_payments - $refunds;
     $this->data['adjustments'] = -($total_payments + $total_admin_adjustment - $refunds);
     $this->data['net'] = number_format((double) ($total + $this->data['adjustments']), 2, '.', '');
     //** Fixes calculations for recurring invoices - should be last to overwrite incorrect values. */
     if ($this->data['type'] == 'recurring') {
         $this->data['total_tax'] = number_format((double) ($this->data['subtotal'] * $avg_tax / 100), 2, '.', '');
         $this->data['net'] = number_format((double) ($this->data['subtotal'] - $this->data['total_discount'] + $this->data['total_tax']), 2, '.', '');
         unset($this->data['adjustments']);
     }
     if ($refunds > 0 && $this->data['total_payments'] <= 0) {
         $this->data['post_status'] = 'refund';
     }
 }
Esempio n. 8
0
 /**
  * Handler for 2Checkout Callback
  * @author Craig Christenson
  * Full callback URL: http://domain/wp-admin/admin-ajax.php?action=wpi_gateway_server_callback&type=wpi_twocheckout
  */
 static function server_callback()
 {
     if (empty($_REQUEST)) {
         die(__('Direct access not allowed', WPI));
     }
     $invoice = new WPI_Invoice();
     $invoice->load_invoice("id={$_REQUEST['merchant_order_id']}");
     /** Verify callback request */
     if (self::_ipn_verified($invoice)) {
         if ($_REQUEST['key']) {
             $event_note = sprintf(__('%s paid via 2Checkout', WPI), WPI_Functions::currency_format(abs($_REQUEST['total']), $_REQUEST['merchant_order_id']));
             $event_amount = (double) $_REQUEST['total'];
             $event_type = 'add_payment';
             /** Log balance changes */
             $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
             /** Log payer email */
             $payer_email = sprintf(__("2Checkout buyer email: %s", WPI), $_REQUEST['email']);
             $invoice->add_entry("attribute=invoice&note={$payer_email}&type=update");
             $invoice->save_invoice();
             /** ... and mark invoice as paid */
             wp_invoice_mark_as_paid($_REQUEST['invoice_id'], $check = true);
             send_notification($invoice->data);
             echo '<script type="text/javascript">window.location="' . get_invoice_permalink($invoice->data['ID']) . '";</script>';
             /** Handle INS messages */
         } elseif ($_POST['md5_hash']) {
             switch ($_POST['message_type']) {
                 case 'FRAUD_STATUS_CHANGED':
                     if ($_POST['fraud_status'] == 'pass') {
                         WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Passed 2Checkout fraud review.', WPI));
                     } elseif (condition) {
                         WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Failed 2Checkout fraud review.', WPI));
                         wp_invoice_mark_as_pending($_POST['vendor_order_id']);
                     }
                     break;
                 case 'RECURRING_STOPPED':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring billing stopped.', WPI));
                     break;
                 case 'RECURRING_INSTALLMENT_FAILED':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring installment failed.', WPI));
                     break;
                 case 'RECURRING_INSTALLMENT_SUCCESS':
                     $event_note = sprintf(__('%1s paid for subscription %2s', WPI), WPI_Functions::currency_format(abs($_POST['item_rec_list_amount_1']), $_POST['vendor_order_id']), $_POST['sale_id']);
                     $event_amount = (double) $_POST['item_rec_list_amount_1'];
                     $event_type = 'add_payment';
                     $invoice->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                     $invoice->save_invoice();
                     send_notification($invoice->data);
                     break;
                 case 'RECURRING_COMPLETE':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring installments completed.', WPI));
                     wp_invoice_mark_as_paid($_POST['invoice'], $check = false);
                     break;
                 case 'RECURRING_RESTARTED':
                     WPI_Functions::log_event(wpi_invoice_id_to_post_id($_POST['vendor_order_id']), 'invoice', 'update', '', __('Recurring sale restarted.', WPI));
                     break;
                 default:
                     break;
             }
         }
     }
 }
    /**
     * Handles validation when somebody is attempting to view an invoice.  
     * If validation is passsed, we add the necessary
     * filters to display the invoice header and page content;
     * Global $invoice_id variable set by WPI_Functions::validate_page_hash();
     */
    function template_redirect() {
      global $wpdb, $invoice_id, $wpi_user_id, $wpi_settings, $wpi_invoice_object, $post;
      
      //** Alwys load styles without checking if given page has an invoice */
      wp_enqueue_style('wpi-theme-specific');
      wp_enqueue_style('wpi-default-style');
      
      /* Determine if the current page is invoice's page */
      if ($wpi_settings['web_invoice_page'] != $post->ID) {
        return;
      }
      
      // If invoice_id is passed, run validate_page_hash  to make sure this is the right page and invoice_id exists
      if (isset($_GET['invoice_id'])) {
        
        if (WPI_Functions::validate_page_hash(mysql_escape_string($_GET['invoice_id']))) {
          
          /** load global invoice object */
          $post_id = wpi_invoice_id_to_post_id($invoice_id);
          
          $wpi_invoice_object = new WPI_Invoice();
          $wpi_invoice_object->load_invoice("id=$post_id");
          $wpi_invoice_object->data;
          
          add_filter('viewable_invoice_types', array( $this, 'viewable_types' ));
          
          //* Determine if current invoice object is "viewable" */
          if(!in_array($wpi_invoice_object->data['post_status'], apply_filters('viewable_invoice_types', array('active')))) {
            return;
          }
          
          // Load front end scripts
          wp_enqueue_script('jquery.validate');
          wp_enqueue_script('wpi-gateways');
          wp_enqueue_script('jquery.maskedinput');
          wp_enqueue_script('wpi-frontend-scripts');

          //** Apply Filters to the invoice description */
          add_action('wpi_description', 'wpautop');
          add_action('wpi_description', 'wptexturize');
          add_action('wpi_description', 'shortcode_unautop');
          add_action('wpi_description', 'convert_chars');
          add_action('wpi_description', 'capital_P_dangit');
          
          // Declare the variable that will hold our AJAX url for JavaScript purposes
          wp_localize_script('jquery', 'wpi_ajax', array( 'url' => admin_url( 'admin-ajax.php' ) ) );
          
          add_action('wp_head', array('WPI_UI', 'frontend_header'));
          
          if ($wpi_settings['replace_page_title_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
            add_action('wp_title', array('WPI_UI', 'wp_title'), 0, 3);
          }
          
          if ($wpi_settings['replace_page_heading_with_subject'] == 'true' || $wpi_settings['hide_page_title'] == 'true') {
            add_action('the_title', array('WPI_UI', 'the_title'), 0, 2);
          }
          
          add_action('the_content', array('WPI_UI', 'the_content'));
          
          if ( $wpi_settings['where_to_display'] == 'replace_tag' ) {
            add_shortcode('wp-invoice', array('WPI_UI', 'the_content_shortcode'));
          }
        
        } else {
          /* Show 404 when invoice doesn't exist */
          $not_found = get_query_template('404');
          require_once $not_found;
          die();
        }
        
      }
      
      // Fixed WordPress filters if page is being opened in HTTPS mode
      if (isset($_SERVER['HTTPS']) && $_SERVER["HTTPS"] == "on") {
        if(function_exists('force_ssl')) {
          add_filter('option_siteurl', 'force_ssl');
          add_filter('option_home', 'force_ssl');
          add_filter('option_url', 'force_ssl');
          add_filter('option_wpurl', 'force_ssl');
          add_filter('option_stylesheet_url', 'force_ssl');
          add_filter('option_template_url', 'force_ssl');
          add_filter('script_loader_src', 'force_ssl');
        }
      }
      
      // Lookup functionality
      if(isset($_POST['wp_invoice_lookup_input'])) {
        header("location:" . get_invoice_permalink($_POST['wp_invoice_lookup_input']));
        //exit;
      }
    }
Esempio n. 10
-1
 /**
  * Process STRIPE payment
  * @global type $invoice
  */
 static function process_payment()
 {
     global $invoice;
     //** Response */
     $response = array('success' => false, 'error' => false, 'data' => null);
     if (isset($_POST['stripeToken'])) {
         $token = $_POST['stripeToken'];
     } else {
         $response['error'] = true;
         $data['messages'][] = __('The order cannot be processed. You have not been charged. Please confirm that you have JavaScript enabled and try again.', WPI);
         $response['data'] = $data;
         die(json_encode($response));
     }
     try {
         if (!class_exists('Stripe')) {
             require_once WPI_Path . '/third-party/stripe/lib/Stripe.php';
         }
         $pk = trim($invoice['billing']['wpi_stripe']['settings'][$invoice['billing']['wpi_stripe']['settings']['mode']['value'] . '_secret_key']['value']);
         Stripe::setApiKey($pk);
         switch ($invoice['type'] == 'recurring') {
             //** If recurring */
             case true:
                 $plan = Stripe_Plan::create(array("amount" => (double) $invoice['net'] * 100, "interval" => $invoice['recurring']['wpi_stripe']['interval'], "interval_count" => $invoice['recurring']['wpi_stripe']['interval_count'], "name" => $invoice['post_title'], "currency" => strtolower($invoice['default_currency_code']), "id" => $invoice['invoice_id']));
                 $customer = Stripe_Customer::create(array("card" => $token, "plan" => $invoice['invoice_id'], "email" => $invoice['user_email']));
                 if (!empty($plan->id) && !empty($plan->amount) && !empty($customer->id)) {
                     $invoice_obj = new WPI_Invoice();
                     $invoice_obj->load_invoice("id={$invoice['invoice_id']}");
                     $log = sprintf(__("Subscription has been initiated. Plan: %s, Customer: %s", WPI), $plan->id, $customer->id);
                     $invoice_obj->add_entry("attribute=invoice&note={$log}&type=update");
                     $invoice_obj->save_invoice();
                     update_post_meta(wpi_invoice_id_to_post_id($invoice['invoice_id']), '_stripe_customer_id', $customer->id);
                     $data['messages'][] = __('Stripe Subscription has been initiated. Do not pay this invoice again. Thank you.', WPI);
                     $response['success'] = true;
                     $response['error'] = false;
                 } else {
                     $data['messages'][] = __('Could not initiate Stripe Subscription. Contact site Administrator please.', WPI);
                     $response['success'] = false;
                     $response['error'] = true;
                 }
                 break;
                 //** If regular payment */
             //** If regular payment */
             case false:
                 //** Support partial payments */
                 if ($invoice['deposit_amount'] > 0) {
                     $amount = (double) $_REQUEST['amount'];
                     if ((double) $_REQUEST['amount'] > $invoice['net']) {
                         $amount = $invoice['net'];
                     }
                     if ((double) $_REQUEST['amount'] < $invoice['deposit_amount']) {
                         $amount = $invoice['deposit_amount'];
                     }
                 } else {
                     $amount = $invoice['net'];
                 }
                 $charge = Stripe_Charge::create(array("amount" => (double) $amount * 100, "currency" => strtolower($invoice['default_currency_code']), "card" => $token, "description" => $invoice['invoice_id'] . ' [' . $invoice['post_title'] . ' / ' . get_bloginfo('url') . ' / ' . $invoice['user_email'] . ']'));
                 if ($charge->paid) {
                     $invoice_id = $invoice['invoice_id'];
                     $wp_users_id = $invoice['user_data']['ID'];
                     //** update user data */
                     update_user_meta($wp_users_id, 'last_name', !empty($_REQUEST['last_name']) ? $_REQUEST['last_name'] : '');
                     update_user_meta($wp_users_id, 'first_name', !empty($_REQUEST['first_name']) ? $_REQUEST['first_name'] : '');
                     update_user_meta($wp_users_id, 'city', !empty($_REQUEST['city']) ? $_REQUEST['city'] : '');
                     update_user_meta($wp_users_id, 'state', !empty($_REQUEST['state']) ? $_REQUEST['state'] : '');
                     update_user_meta($wp_users_id, 'zip', !empty($_REQUEST['zip']) ? $_REQUEST['zip'] : '');
                     update_user_meta($wp_users_id, 'streetaddress', !empty($_REQUEST['address1']) ? $_REQUEST['address1'] : '');
                     update_user_meta($wp_users_id, 'phonenumber', !empty($_REQUEST['phonenumber']) ? $_REQUEST['phonenumber'] : '');
                     update_user_meta($wp_users_id, 'country', !empty($_REQUEST['country']) ? $_REQUEST['country'] : '');
                     if (!empty($_REQUEST['crm_data'])) {
                         self::user_meta_updated($_REQUEST['crm_data']);
                     }
                     $invoice_obj = new WPI_Invoice();
                     $invoice_obj->load_invoice("id={$invoice['invoice_id']}");
                     $amount = (double) ($charge->amount / 100);
                     //** Add payment amount */
                     $event_note = WPI_Functions::currency_format($amount, $invoice['invoice_id']) . __(" paid via STRIPE", WPI);
                     $event_amount = $amount;
                     $event_type = 'add_payment';
                     $event_note = urlencode($event_note);
                     //** Log balance changes */
                     $invoice_obj->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                     //** Log client IP */
                     $success = __("Successfully processed by ", WPI) . $_SERVER['REMOTE_ADDR'];
                     $invoice_obj->add_entry("attribute=invoice&note={$success}&type=update");
                     //** Log payer */
                     $payer_card = __("STRIPE Card ID: ", WPI) . $charge->card->id;
                     $invoice_obj->add_entry("attribute=invoice&note={$payer_card}&type=update");
                     $invoice_obj->save_invoice();
                     //** Mark invoice as paid */
                     wp_invoice_mark_as_paid($invoice_id, $check = true);
                     send_notification($invoice);
                     $data['messages'][] = __('Successfully paid. Thank you.', WPI);
                     $response['success'] = true;
                     $response['error'] = false;
                 } else {
                     $data['messages'][] = $charge->failure_message;
                     $response['success'] = false;
                     $response['error'] = true;
                 }
                 break;
                 //** Other cases */
             //** Other cases */
             default:
                 break;
         }
         $response['data'] = $data;
         die(json_encode($response));
     } catch (Stripe_CardError $e) {
         $e_json = $e->getJsonBody();
         $err = $e_json['error'];
         $response['error'] = true;
         $data['messages'][] = $err['message'];
     } catch (Stripe_ApiConnectionError $e) {
         $response['error'] = true;
         $data['messages'][] = __('Service is currently unavailable. Please try again later.', WPI);
     } catch (Stripe_InvalidRequestError $e) {
         $response['error'] = true;
         $data['messages'][] = __('Unknown error occured. Please contact site administrator.', WPI);
     } catch (Stripe_ApiError $e) {
         $response['error'] = true;
         $data['messages'][] = __('Stripe server is down! Try again later.', WPI);
     } catch (Exception $e) {
         $response['error'] = true;
         $data['messages'][] = $e->getMessage();
     }
     $response['data'] = $data;
     die(json_encode($response));
 }