Esempio n. 1
1
 /**
  * @param array $process_data
  * @param $blog_id
  * @param $domain
  *
  * @return bool
  */
 public static function process_checkout_form($process_data = array(), $blog_id, $domain)
 {
     global $psts, $current_user, $current_site;
     $site_name = $current_site->site_name;
     $img_base = $psts->plugin_url . 'images/';
     $session_keys = array('new_blog_details', 'upgraded_blog_details', 'COUPON_CODE', 'activation_key');
     foreach ($session_keys as $key) {
         $process_data[$key] = isset($process_data[$key]) ? $process_data[$key] : ProSites_Helper_Session::session($key);
     }
     if (!empty($domain)) {
         $site_name = !empty($_POST['blogname']) ? $_POST['blogname'] : !empty($_POST['signup_email']) ? $_POST['signup_email'] : '';
     }
     //Process Checkout
     if (isset($_POST['cc_stripe_checkout']) && 1 == (int) $_POST['cc_stripe_checkout']) {
         //check for level, if empty don't go ahead and return
         if (empty($_POST['level']) || empty($_POST['period'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return false;
         } else {
             if (!isset($_POST['stripeToken']) && empty($_POST['wp_password'])) {
                 $psts->errors->add('general', __('There was an error processing your Credit Card with Stripe. Please try again.', 'psts'));
             }
         }
         // TAX Object
         $tax_object = ProSites_Helper_Session::session('tax_object');
         if (empty($tax_object) || empty($tax_object->evidence)) {
             $tax_object = ProSites_Helper_Tax::get_tax_object();
             ProSites_Helper_Session::session('tax_object', $tax_object);
         }
         $evidence_string = ProSites_Helper_Tax::get_evidence_string($tax_object);
         $error = '';
         $success = '';
         $plan = self::get_plan_id($_POST['level'], $_POST['period']);
         $customer_id = '';
         $current_plan_level = 0;
         $activation_key = isset($_POST['activation']) ? $_POST['activation'] : '';
         $email = !empty($_POST['user_email']) ? $_POST['user_email'] : (!empty($_POST['signup_email']) ? $_POST['signup_email'] : (!empty($_POST['blog_email']) ? $_POST['blog_email'] : ''));
         $blog_id = !empty($blog_id) ? $blog_id : isset($_REQUEST['bid']) ? (int) $_REQUEST['bid'] : 0;
         //If there is a blog id, fetch existing customer details (Upgrade)
         if (!empty($blog_id)) {
             $customer_id = self::get_customer_data($blog_id)->customer_id;
             $email = isset($current_user->user_email) ? $current_user->user_email : get_blog_option($blog_id, 'admin_email');
             //Get current plan for the user
             if ($current_plan = self::get_current_plan($blog_id)) {
                 list($current_plan_level, $current_plan_period) = explode('_', $current_plan);
             }
         } else {
             //New Signup
             if (empty($email) && isset($process_data['new_blog_details']) && isset($process_data['new_blog_details']['user_email'])) {
                 $email = $process_data['new_blog_details']['user_email'];
             }
             $customer_id = self::get_customer_data(false, false, $email)->customer_id;
         }
         if (!self::plan_exists($plan)) {
             $psts->errors->add('general', sprintf(__('Stripe plan %1$s does not exist.', 'psts'), $plan));
             return;
         }
         //Create s Stripe profile for the customer with all the available details,
         //If customer already exists, retrieve customer from stripe
         try {
             if (!$customer_id) {
                 try {
                     $customer_args = array('email' => $email, 'description' => sprintf(__('%s user', 'psts'), $site_name), 'card' => $_POST['stripeToken'], 'metadata' => array('domain' => $domain));
                     $user = get_user_by('email', $email);
                     if ($user) {
                         $blog_string = '';
                         $customer_args['metadata']['user'] = $user->user_login;
                         $customer_args['description'] = sprintf(__('%s user - %s ', 'psts'), $site_name, $user->first_name . ' ' . $user->last_name);
                         $user_blogs = get_blogs_of_user($user->ID);
                         foreach ($user_blogs as $user_blog) {
                             $blog_string .= $user_blog->blogname . ', ';
                         }
                         $customer_args['metadata']['blogs'] = $blog_string;
                     }
                     if (!$domain) {
                         unset($customer_args['metadata']['domain']);
                     }
                     $c = Stripe_Customer::create($customer_args);
                 } catch (Exception $e) {
                     $psts->errors->add('general', __('The Stripe customer could not be created. Please try again.', 'psts'));
                     return;
                 }
                 //Update the stripe customer id, this is temporary, will be overridden by subscription or charge id
                 self::set_customer_data($blog_id, $c->id, 'ak_' . $activation_key);
                 $customer_id = $c->id;
                 $new = true;
             } else {
                 // Get a customer if they exist
                 try {
                     $c = Stripe_Customer::retrieve($customer_id);
                 } catch (Exception $e) {
                     $psts->errors->add('general', __('The Stripe customer could not be retrieved. Please try again.', 'psts'));
                     return;
                 }
                 $c->description = sprintf(__('%s user', 'psts'), $site_name);
                 $c->email = $email;
                 $user = get_user_by('email', $email);
                 if ($user) {
                     $blog_string = '';
                     $c->metadata->user = $user->user_login;
                     $c->description = sprintf(__('%s user - %s ', 'psts'), $site_name, $user->first_name . ' ' . $user->last_name);
                     $user_blogs = get_blogs_of_user($user->ID);
                     foreach ($user_blogs as $user_blog) {
                         $blog_string .= $user_blog->blogname . ', ';
                     }
                     $c->metadata->blogs = $blog_string;
                 }
                 $c->save();
                 $new = false;
                 //validate wp password (if applicable)
                 if (!empty($_POST['wp_password']) && !wp_check_password($_POST['wp_password'], $current_user->data->user_pass, $current_user->ID)) {
                     $psts->errors->add('general', __('The password you entered is incorrect.', 'psts'));
                     return;
                 }
             }
             //prepare vars
             $currency = self::currency();
             $amount_off = false;
             $paymentAmount = $initAmount = $psts->get_level_setting($_POST['level'], 'price_' . $_POST['period']);
             $trial_days = $psts->get_setting('trial_days', 0);
             $cp_code = false;
             $setup_fee = (double) $psts->get_setting('setup_fee', 0);
             $has_coupon = isset($process_data['COUPON_CODE']) && ProSites_Helper_Coupons::check_coupon($process_data['COUPON_CODE'], $blog_id, $_POST['level'], $_POST['period'], $domain) ? true : false;
             $has_setup_fee = $psts->has_setup_fee($blog_id, $_POST['level']);
             $recurring = $psts->get_setting('recurring_subscriptions', 1);
             if ($has_setup_fee) {
                 $initAmount = $setup_fee + $paymentAmount;
             }
             if ($has_coupon || $has_setup_fee) {
                 $lifetime = 'once';
                 if ($has_coupon) {
                     //apply coupon
                     $adjusted_values = ProSites_Helper_Coupons::get_adjusted_level_amounts($process_data['COUPON_CODE']);
                     $coupon_obj = ProSites_Helper_Coupons::get_coupon($process_data['COUPON_CODE']);
                     $lifetime = isset($coupon_obj['lifetime']) && 'indefinite' == $coupon_obj['lifetime'] ? 'forever' : 'once';
                     //	$coupon_value = $psts->coupon_value( $process_data['COUPON_CODE'], $paymentAmount );
                     $coupon_value = $adjusted_values[$_POST['level']]['price_' . $_POST['period']];
                     // $amount_off   = $paymentAmount - $coupon_value['new_total'];
                     $amount_off = $paymentAmount - $coupon_value;
                     $initAmount -= $amount_off;
                     $initAmount = 0 > $initAmount ? 0 : $initAmount;
                     // avoid negative
                     $cpn = false;
                     //Create a stripe coupon if it doesn't exists already
                     try {
                         $cpn = Stripe_Coupon::create(array('amount_off' => $amount_off * 100, 'duration' => $lifetime, 'currency' => $currency, 'max_redemptions' => 1));
                     } catch (Exception $e) {
                         $psts->errors->add('general', __('Temporary Stripe coupon could not be generated correctly. Please try again.', 'psts'));
                         return;
                     }
                     $cp_code = $cpn->id;
                 }
                 //Check if it's a recurring subscription
                 if ($recurring) {
                     $recurringAmmount = 'forever' == $lifetime && $has_coupon ? $coupon_value : $paymentAmount;
                     if ($_POST['period'] == 1) {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first month, then %2$s each month', 'psts'), $psts->format_currency($currency, $initAmount), $psts->format_currency($currency, $recurringAmmount));
                     } else {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first %2$s month period, then %3$s every %4$s months', 'psts'), $psts->format_currency($currency, $initAmount), $_POST['period'], $psts->format_currency($currency, $recurringAmmount), $_POST['period']);
                     }
                 } else {
                     if (!empty($blog_id)) {
                         $initAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $initAmount);
                     }
                     if ($_POST['period'] == 1) {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $initAmount));
                     } else {
                         $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $initAmount), $_POST['period']);
                     }
                 }
             } elseif ($recurring) {
                 if ($_POST['period'] == 1) {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s each month', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency);
                 } else {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every %3$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency, $_POST['period']);
                 }
             } else {
                 //New Signups
                 if (!empty($blog_id)) {
                     $paymentAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $paymentAmount);
                 }
                 if ($_POST['period'] == 1) {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $paymentAmount));
                 } else {
                     $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $_POST['period']);
                 }
             }
             // Override the Stripe description
             $desc = apply_filters('psts_stripe_checkout_desc', $desc, $_POST['period'], $_POST['level'], $paymentAmount, $initAmount, $blog_id, $domain);
             // Time to process invoices with Stripe
             if ($recurring) {
                 // Recurring subscription
                 // Assign plan to customer
                 $args = array("plan" => $plan, "prorate" => true);
                 // Apply tax?
                 if ($tax_object->apply_tax) {
                     $args['tax_percent'] = $tax_object->tax_rate * 100;
                 }
                 // If there is a coupon, add its reference
                 if ($cp_code) {
                     $args["coupon"] = $cp_code;
                 }
                 // If this is a trial before the subscription starts
                 if ($psts->is_trial_allowed($blog_id)) {
                     if (isset($process_data['new_blog_details']) || !$psts->is_existing($blog_id)) {
                         //customer is new - add trial days
                         $args['trial_end'] = strtotime('+ ' . $trial_days . ' days');
                     } elseif (is_pro_trial($blog_id) && $psts->get_expire($blog_id) > time()) {
                         //customer's trial is still valid - carry over existing expiration date
                         $args['trial_end'] = $psts->get_expire($blog_id);
                     }
                 }
                 // Meta data for `pay before blog` creation
                 $args['metadata'] = array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level']);
                 if ($tax_object->apply_tax) {
                     $args['metadata']['tax_evidence'] = $evidence_string;
                 }
                 if (!$domain) {
                     unset($args['metadata']['domain']);
                 }
                 // new blog
                 if (isset($_POST['activation'])) {
                     $args['metadata']['activation'] = $_POST['activation'];
                 }
                 // Create Stripe Invoice for the setup fee
                 if ($has_setup_fee) {
                     try {
                         $customer_args = array('customer' => $customer_id, 'amount' => $setup_fee * 100, 'currency' => $currency, 'description' => __('One-time setup fee', 'psts'), 'metadata' => array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level'], 'setup_fee' => 'yes'));
                         if ($tax_object->apply_tax) {
                             $customer_args['metadata']['tax_evidence'] = $evidence_string;
                         }
                         if (!$domain) {
                             unset($customer_args['metadata']['domain']);
                         }
                         // new blog
                         if (isset($_POST['activation'])) {
                             $customer_args['metadata']['activation'] = $_POST['activation'];
                         }
                         Stripe_InvoiceItem::create($customer_args);
                     } catch (Exception $e) {
                         wp_mail(get_blog_option($blog_id, 'admin_email'), __('Error charging setup fee. Attention required!', 'psts'), sprintf(__('An error occurred while charging a setup fee of %1$s to Stripe customer %2$s. You will need to manually process this amount.', 'psts'), $psts->format_currency($currency, $setup_fee), $customer_id));
                     }
                 }
                 // Create/update subscription
                 try {
                     $result = false;
                     $sub = false;
                     // Brand new blog...
                     if (empty($blog_id)) {
                         $result = $c->subscriptions->create($args);
                     } else {
                         $customer_data = self::get_customer_data($blog_id);
                         try {
                             $sub = $c->subscriptions->retrieve($customer_data->subscription_id);
                             $sub_id = $sub->id;
                             $prev_plan = $sub->plan->id;
                             $sub->plan = isset($args['plan']) ? $args['plan'] : $sub->plan;
                             $changed_plan = $sub->plan;
                             $sub->prorate = isset($args['prorate']) ? $args['prorate'] : $sub->prorate;
                             if (isset($args['coupon'])) {
                                 $sub->coupon = $args['coupon'];
                             }
                             if (isset($args['trial_end'])) {
                                 $sub->trial_end = $args['trial_end'];
                             }
                             $sub->metadata->period = $args['metadata']['period'];
                             $sub->metadata->level = $args['metadata']['level'];
                             if (isset($args['metadata']['activation'])) {
                                 $sub->metadata->activation = $args['metadata']['activation'];
                             } else {
                                 $activation_key = ProSites_Helper_ProSite::get_activation_key($blog_id);
                                 if (!empty($activation_key)) {
                                     $sub->metadata->activation = $activation_key;
                                 }
                             }
                             $sub->metadata->blog_id = $blog_id;
                             if (isset($args['metadata']['domain'])) {
                                 $sub->metadata->domain = $args['metadata']['domain'];
                             }
                             // Apply tax?
                             if ($tax_object->apply_tax) {
                                 $sub->tax_percent = $tax_object->tax_rate * 100;
                                 $sub->metadata->tax_evidence = $evidence_string;
                             }
                             $sub->save();
                             // As per Stripe API, to charge immediately, apply an invoice now
                             if ($prev_plan != $changed_plan) {
                                 $customer_args = array('customer' => $customer_id, 'subscription' => $sub_id, 'metadata' => array('plan_change' => 'yes'));
                                 $invoice = Stripe_Invoice::create($customer_args);
                                 $invoice = $invoice->pay();
                                 $plan_parts = explode('_', $changed_plan);
                                 $new_period = array_pop($plan_parts);
                                 $new_level = array_pop($plan_parts);
                                 $plan_parts = explode('_', $prev_plan);
                                 $prev_period = array_pop($plan_parts);
                                 $prev_level = array_pop($plan_parts);
                                 $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $new_level, 'period' => $new_period, 'prev_level' => $prev_level, 'prev_period' => $prev_period);
                                 ProSites_Helper_Session::session('plan_updated', $updated);
                             }
                         } catch (Exception $e) {
                             // Fall through...
                         }
                         // Additional blog
                         if (empty($sub)) {
                             $args['metadata']['blog_id'] = $blog_id;
                             if (!isset($args['metadata']['activation'])) {
                                 $activation_key = ProSites_Helper_ProSite::get_activation_key($blog_id);
                                 if (!empty($activation_key)) {
                                     $args['metadata']['activation'] = $activation_key;
                                 }
                             }
                             $result = $c->subscriptions->create($args);
                         }
                         // This one is now deprecated
                         // $result = $c->updateSubscription( $args );
                     }
                     // Capture success as soon as we can!
                     if (!empty($result)) {
                         $sub_id = $result->id;
                         $plan = $result->plan;
                         $plan_parts = explode('_', $plan->id);
                         $period = array_pop($plan_parts);
                         $level = array_pop($plan_parts);
                         $trial = isset($plan->status) && 'trialing' == $plan->status ? true : false;
                         $expire = $trial ? $plan->trial_end : $result->current_period_end;
                         $result = ProSites_Helper_Registration::activate_blog($activation_key, $trial, $period, $level, $expire);
                         $blog_id = $result['blog_id'];
                         if (isset($process_data['new_blog_details'])) {
                             ProSites_Helper_Session::session(array('new_blog_details', 'blog_id'), $blog_id);
                             ProSites_Helper_Session::session(array('new_blog_details', 'payment_success'), true);
                         } else {
                             ProSites_Helper_Session::session('upgrade_blog_details', array());
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'blog_id'), $blog_id);
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'level'), $level);
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'period'), $period);
                             ProSites_Helper_Session::session(array('upgrade_blog_details', 'payment_success'), true);
                         }
                         self::set_customer_data($blog_id, $customer_id, $sub_id);
                     }
                     if ($current_plan = self::get_current_plan($blog_id)) {
                         list($current_plan_level, $current_plan_period) = explode('_', $current_plan);
                     }
                     //Extend the Blog Subscription
                     $old_expire = $psts->get_expire($blog_id);
                     $new_expire = $old_expire && $old_expire > time() ? $old_expire : false;
                     $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $initAmount, $new_expire, false);
                     //$psts->email_notification( $blog_id, 'receipt' );
                     if (isset($current_plan_level)) {
                         if ($current_plan_level > $_POST['level']) {
                             $psts->record_stat($blog_id, 'upgrade');
                         } else {
                             $psts->record_stat($blog_id, 'modify');
                         }
                     } else {
                         $psts->record_stat($blog_id, 'signup');
                     }
                     // Update the sub with the new blog id (old subscriptions will update later).
                     if (!empty($blog_id)) {
                         $sub = $c->subscriptions->retrieve($sub_id);
                         $sub->metadata->blog_id = $blog_id;
                         $sub->save();
                     }
                 } catch (Exception $e) {
                     $body = $e->getJsonBody();
                     $error = $body['error'];
                     $psts->errors->add('general', $error['message']);
                     return;
                 }
             } else {
                 // Not a subscription, this is a one of payment, charged for 1 term
                 try {
                     if (!empty($blog_id)) {
                         $initAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $initAmount);
                         //If activation key is empty
                         $activation_key = !empty($activation_key) ? $activation_key : ProSites_Helper_ProSite::get_activation_key($blog_id);
                     }
                     if ($tax_object->apply_tax) {
                         $amount = $initAmount + $initAmount * $tax_object->tax_rate;
                         $desc += sprintf(__('(includes tax of %s%% [%s])', 'psts'), $tax_object->tax_rate * 100, $tax_object->country);
                     } else {
                         $amount = $initAmount;
                     }
                     $customer_args = array('customer' => $customer_id, 'amount' => $amount * 100, 'currency' => $currency, 'description' => $desc, 'metadata' => array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level']));
                     if ($tax_object->apply_tax) {
                         $customer_args['metadata']['tax_evidence'] = $evidence_string;
                     }
                     if (!$domain) {
                         unset($customer_args['metadata']['domain']);
                     }
                     // new blog
                     if (isset($_POST['activation'])) {
                         $customer_args['metadata']['activation'] = $_POST['activation'];
                     }
                     /**
                      * 1 off charge of not trialing, but if trialing, just send a zero-dollar invoice
                      */
                     if (empty($trial_days) || 0 == $customer_args['amount']) {
                         $result = Stripe_Charge::create($customer_args);
                     } else {
                         $result = Stripe_InvoiceItem::create($customer_args);
                     }
                     // Capture success as soon as we can!
                     if ($result) {
                         $period = (int) $_POST['period'];
                         $level = (int) $_POST['level'];
                         $signup_details = ProSites_Helper_Registration::activate_blog($activation_key, false, $period, $level);
                         $blog_id = $signup_details['blog_id'];
                         if (isset($process_data['new_blog_details'])) {
                             ProSites_Helper_Session::session(array('new_blog_details', 'blog_id'), $blog_id);
                             ProSites_Helper_Session::session(array('new_blog_details', 'payment_success'), true);
                         }
                         self::set_customer_data($blog_id, $customer_id, $result->id);
                     }
                     if ($current_plan = self::get_current_plan($blog_id)) {
                         list($current_plan_level, $current_plan_period) = explode('_', $current_plan);
                     }
                     $old_expire = $psts->get_expire($blog_id);
                     $new_expire = $old_expire && $old_expire > time() ? $old_expire : false;
                     $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $initAmount, $new_expire, false);
                     //$psts->email_notification( $blog_id, 'receipt' );
                     if (isset($current_plan_level)) {
                         if ($current_plan_level > $_POST['level']) {
                             $psts->record_stat($blog_id, 'upgrade');
                         } else {
                             $psts->record_stat($blog_id, 'modify');
                         }
                     } else {
                         $psts->record_stat($blog_id, 'signup');
                     }
                 } catch (Stripe_CardError $e) {
                     $body = $e->getJsonBody();
                     $err = $body['error'];
                     $psts->errors->add('general', $e['message']);
                 } catch (Exception $e) {
                     $psts->errors->add('general', __('An unknown error occurred while processing your payment. Please try again.', 'psts'));
                 }
             }
             //delete the temporary coupon code
             if ($cp_code) {
                 try {
                     $cpn = Stripe_Coupon::retrieve($cp_code);
                     $cpn->delete();
                 } catch (Exception $e) {
                     wp_mail(get_blog_option($blog_id, 'admin_email'), __('Error deleting temporary Stripe coupon code. Attention required!.', 'psts'), sprintf(__('An error occurred when attempting to delete temporary Stripe coupon code %1$s. You will need to manually delete this coupon via your Stripe account.', 'psts'), $cp_code));
                 }
                 $psts->use_coupon($process_data['COUPON_CODE'], $blog_id, $domain);
             }
             if ($new || $psts->is_blog_canceled($blog_id)) {
                 // Added for affiliate system link
                 if ($recurring) {
                     $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Customer ID: %2$s', 'psts'), $desc, $customer_id), $domain);
                 } else {
                     $psts->log_action($blog_id, sprintf(__('User completed new payment via CC: Site created/extended (%1$s) - Customer ID: %2$s', 'psts'), $desc, $customer_id), $domain);
                 }
                 do_action('supporter_payment_processed', $blog_id, $paymentAmount, $_POST['period'], $_POST['level']);
             } else {
                 $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: Plan changed to (%1$s) - %2$s', 'psts'), $desc, $customer_id), $domain);
             }
             //display GA ecommerce in footer
             $psts->create_ga_ecommerce($blog_id, $_POST['period'], $initAmount, $_POST['level'], $site_name, $domain);
             if (!empty($blog_id)) {
                 update_blog_option($blog_id, 'psts_stripe_canceled', 0);
                 /* 	some times there is a lag receiving webhooks from Stripe. we want to be able to check for that
                 				and display an appropriate message to the customer (e.g. there are changes pending to your account) */
                 update_blog_option($blog_id, 'psts_stripe_waiting', 1);
             } else {
                 if (isset($process_data['activation_key'])) {
                     //Update signup meta
                     $key = $process_data['activation_key'];
                     $signup_meta = '';
                     $signup_meta = $psts->get_signup_meta($key);
                     $signup_meta['psts_stripe_canceled'] = 0;
                     $signup_meta['psts_stripe_waiting'] = 1;
                     $psts->update_signup_meta($signup_meta, $key);
                 }
             }
             update_blog_option($blog_id, 'psts_stripe_waiting', 1);
             if (empty(self::$complete_message)) {
                 // Message is redundant now, but still used as a flag.
                 self::$complete_message = __('Your payment was successfully recorded! You should be receiving an email receipt shortly.', 'psts');
             }
         } catch (Exception $e) {
             $psts->errors->add('general', $e->getMessage());
         }
     }
 }
Esempio n. 2
0
 /**
  * @param $blog_id
  *   This function will handler
  *   Checkout process
  *   -With Coupon
  *   -Without Coupon
  *   -Recurring
  *   -One time
  *   -DownGrade level
  *   -UpGrade level
  *   -Manual extends subscription time
  */
 public function process_checkout($blog_id, $domain = false)
 {
     global $current_site, $current_user, $psts, $wpdb;
     $site_name = $current_site->site_name;
     if (!empty($domain)) {
         //Get blog name from signup as per WP Signup or BP Signup
         $site_name = $domain;
     }
     //Processing User submitted form
     if (isset($_POST['2co_checkout_button'])) {
         //validate
         if (!$this->check_nonce()) {
             $psts->errors->add('general', __('Whoops, looks like you may have tried to submit your payment twice so we prevented it. Check your subscription info below to see if it was created. If not, please try again.', 'psts'));
         }
         if (!isset($_POST['period']) || !isset($_POST['level'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return;
         }
         //If free level is selected, activate a trial
         if (!empty($domain) && !$psts->prevent_dismiss() && '0' === $_POST['level'] && '0' === $_POST['period']) {
             $psts->activate_user_blog($domain, true, $_POST['level'], $_POST['period']);
             $esc_domain = esc_url($domain);
             //Set complete message
             $this->complete_message = __('Your trial blog has been setup at <a href="' . $esc_domain . '">' . $esc_domain . '</a>', 'psts');
             return;
         }
         add_action('wp_head', array(&$this, 'checkout_js'));
         wp_enqueue_script(array('jquery'));
         //prepare vars
         $amount_off = false;
         $payment_amount = $init_amount = $psts->get_level_setting($_POST['level'], 'price_' . $_POST['period']);
         $trial_days = $psts->get_setting('trial_days', 0);
         $cp_code = false;
         $is_trial = $psts->is_trial_allowed($blog_id);
         $setup_fee = (double) $psts->get_setting('setup_fee', 0);
         $has_coupon = isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_POST['level']) ? true : false;
         $has_setup_fee = $psts->has_setup_fee($blog_id, $_POST['level']);
         $recurring = $psts->get_setting('recurring_subscriptions', 1);
         $params = array('sid' => $psts->get_setting('2co_acc_number'), 'currency' => $psts->get_setting('2co_currency', 'USD'), 'x_receipt_link_url' => $psts->checkout_url($blog_id, $domain), 'mode' => '2CO', 'merchant_order_id' => $blog_id, 'period' => esc_attr($_POST['period']), 'level' => esc_attr($_POST['level']), '2co_cart_type' => 'ProSites', 'demo' => $psts->get_setting('2co_checkout_mode'));
         //build products params
         $addition_params = array('li_0_type' => 'product', 'li_0_name' => $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name'), 'li_0_price' => $init_amount);
         //if have setup fee
         if ($has_setup_fee) {
             $addition_params['li_0_startup_fee'] = $setup_fee;
         }
         //if have trial time
         if ($is_trial) {
             $init_amount = $init_amount - $payment_amount;
         }
         //case have coupon
         if ($has_coupon) {
             $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $payment_amount);
             $amount_off = $payment_amount - $coupon_value['new_total'];
             $init_amount -= $amount_off;
             $addition_params = array_merge($addition_params, array('li_1_type' => 'coupon', 'li_1_name' => $_SESSION['COUPON_CODE'], 'li_1_price' => $amount_off));
         }
         if ($recurring) {
             $addition_params = array_merge($addition_params, array('li_0_recurrence' => esc_attr($_POST['period']) . ' Month', 'li_0_duration' => 'Forever'));
         }
         //check if this is downgrade,require no money
         if (!empty($blog_id)) {
             $cur_level = $psts->get_level($blog_id);
             //To Do: Update downgrade logic, to avoid free subscription for next period if downgraded at the end of subscription
             if ($cur_level > 0) {
                 if ($cur_level > $_POST['level']) {
                     /**
                      * Case downgrade
                      * If period is same,so it is simple.When the current level expire,we will downgrade the leve.
                      * For cost for first period of new level will be nearly free.
                      */
                     $old = $wpdb->get_row($wpdb->prepare("SELECT expire, level, term, amount FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = %d", $blog_id));
                     if ($old->term == $_POST['period']) {
                         $addition_params = array_merge($addition_params, array_merge(array('li_2_type' => 'coupon', 'li_2_name' => __('First month is free due to new level apply to next month', 'ptst'), 'li_2_price' => $init_amount - 0.01)));
                     } elseif ($old->term < $_POST['period'] || $old->term > $_POST['period']) {
                         /**
                          * This case is when the new period smaller than current or larger
                          * 2checkout not support for update customer infomation,
                          * and the only way is using the checkout.Some issue will happend
                          * Example current is 3 months,but user want to downgrade to 1 month.The point is if we subscription for client now,it will
                          * make client need to pay for 3 months before the old expire end. So for this case,we only cancel the subscription,
                          * and send the checkout url when this subscrition expire via email.
                          */
                         update_option('psts_2co_recuring_next_plan', array('action' => 'downgrade', 'level' => $_POST['level'], 'type' => 'email'));
                         $this->complete_message = __('Your 2Checkout subscription modification was not done automate! You will recive an email about the new upgrade when current subsciprion expire.', 'psts');
                     }
                 } elseif ($cur_level < $_POST['level']) {
                     /**
                      * Case upgrade
                      */
                     //get the unuse balance
                     $balance_left = $this->cal_unused_balance($blog_id);
                     $addition_params = array_merge($addition_params, array_merge(array('li_2_type' => 'coupon', 'li_2_name' => __('Balance left of last subscription', 'ptst'), 'li_2_price' => $balance_left)));
                 }
             }
         }
         //create form
         $params = array_merge($params, $addition_params);
         $this->set_gateway_param();
         //all set,now generate the form and submit
         Twocheckout_Charge::redirect($params, 'checkout');
         exit;
     } elseif (isset($_REQUEST['credit_card_processed']) && strtolower($_REQUEST['credit_card_processed']) == 'y') {
         //Processing 2checkout response after user returns from 2checkout site
         $check = Twocheckout_Return::check($_REQUEST, $psts->get_setting('2co_secret_word'), 'array');
         if ($check['response_code'] == 'Success') {
             //Activate the blog
             $blog_id = $psts->activate_user_blog($domain);
             if (!$this->check_profile_id_exist($blog_id, $_REQUEST['order_number'])) {
                 //profile not exist
                 //do the check
                 //get current level
                 $cur_level = $psts->get_level($blog_id);
                 $modify = false;
                 if (is_pro_site($blog_id) && !is_pro_trial($blog_id)) {
                     $modify = true;
                     if ($cur_level != 0 && $cur_level == $_REQUEST['level']) {
                         $modify = false;
                     }
                 }
                 //now go
                 if ($modify) {
                     //this case user is modify the subscription,we will need to check upgrade or downgrade,and refund the diff
                     $scenario = '';
                     if ($cur_level < $_REQUEST['level']) {
                         $scenario = 'upgrade';
                     } elseif ($cur_level > $_REQUEST['level']) {
                         $scenario = 'downgrade';
                     }
                     $this->tcheckout_modify_subscription($blog_id, $scenario);
                 } elseif ($modify == false && (is_pro_site($blog_id) && !is_pro_trial($blog_id))) {
                     //site is in subscription,but user extend to longer
                     //$this->tcheckout_modify_subscription( $blog_id, 'extend' );
                 } else {
                     $this->tcheckout_hander_new_subscription($blog_id);
                 }
             } else {
                 $psts->errors->add('general', __('Your transaction has already settled!', 'psts'));
             }
         } else {
             $psts->errors->add('general', __('There was a problem validating the 2Checkout payment:<br /><strong>MD5 Hash did not match!</strong><br />Please contact the seller directly for assistance.', 'psts'));
         }
     }
 }
 /**
  * Check if user is upgrading or downgrading
  *
  * @param $blog_id
  * @param $post
  */
 private static function is_modifying($blog_id, $post, $initAmount)
 {
     global $psts;
     $modify = false;
     $level = !empty($post['level']) ? $post['level'] : '';
     $period = !empty($post['period']) ? $post['period'] : '';
     if (empty($blog_id) || empty($level) || empty($period)) {
         return false;
     }
     //Check if there is existing profile id
     $profile_id = self::get_profile_id($blog_id);
     if (!empty($profile_id)) {
         //Get details from Paypal
         $profile_details = PaypalApiHelper::GetRecurringPaymentsProfileDetails($profile_id);
         //Check if there is any profile reference
         $profile_ref = !empty($profile_details['PROFILEREFERENCE']) ? $profile_details['PROFILEREFERENCE'] : '';
         if (!empty($profile_ref)) {
             //Get Existing plan details from reference
             list($pre, $blog_id, $prev_level, $prev_period, $amount, $currency, $timestamp, $activation_key) = explode('_', $profile_ref);
         }
         if ($period != $prev_period || $level != $prev_level) {
             $modify = true;
         }
     }
     if ($modify) {
         //check for modifying
         if (!empty($blog_id) && is_pro_site($blog_id) && !is_pro_trial($blog_id)) {
             $modify = $psts->calc_upgrade($blog_id, $initAmount, $level, $period);
             $modify = $modify ? $modify : $psts->get_expire($blog_id);
         } else {
             $modify = false;
         }
     }
     return $modify;
 }
Esempio n. 4
0
    function checkout_screen($content, $blog_id)
    {
        global $psts, $wpdb, $current_site, $current_user;
        if (!$blog_id) {
            return $content;
        }
        //cancel subscription
        if (isset($_GET['action']) && $_GET['action'] == 'cancel' && wp_verify_nonce($_GET['_wpnonce'], 'psts-cancel')) {
            $error = '';
            try {
                $customer_id = $this->get_customer_id($blog_id);
                $cu = Stripe_Customer::retrieve($customer_id);
                $cu->cancelSubscription();
            } catch (Exception $e) {
                $error = $e->getMessage();
            }
            if ($error != '') {
                $content .= '<div id="message" class="error fade"><p>' . __('There was a problem canceling your subscription, please contact us for help: ', 'psts') . $error . '</p></div>';
            } else {
                //record stat
                $psts->record_stat($blog_id, 'cancel');
                $psts->email_notification($blog_id, 'canceled');
                update_blog_option($blog_id, 'psts_stripe_canceled', 1);
                $end_date = date_i18n(get_option('date_format'), $psts->get_expire($blog_id));
                $psts->log_action($blog_id, sprintf(__('Subscription successfully cancelled by %1$s. They should continue to have access until %2$s', 'psts'), $current_user->display_name, $end_date));
                $content .= '<div id="message" class="updated fade"><p>' . sprintf(__('Your %1$s subscription has been canceled. You should continue to have access until %2$s.', 'psts'), $current_site->site_name . ' ' . $psts->get_setting('rebrand'), $end_date) . '</p></div>';
            }
        }
        $cancel_status = get_blog_option($blog_id, 'psts_stripe_canceled');
        $cancel_content = '';
        $img_base = $psts->plugin_url . 'images/';
        $pp_active = false;
        //hide top part of content if its a pro blog
        if (is_pro_site($blog_id) || $psts->errors->get_error_message('coupon')) {
            $content = '';
        }
        if ($errmsg = $psts->errors->get_error_message('general')) {
            $content = '<div id="psts-general-error" class="psts-error">' . $errmsg . '</div>';
            //hide top part of content if theres an error
        }
        //if transaction was successful display a complete message and skip the rest
        if ($this->complete_message) {
            $content = '<div id="psts-complete-msg">' . $this->complete_message . '</div>';
            $content .= '<p>' . $psts->get_setting('stripe_thankyou') . '</p>';
            $content .= '<p><a href="' . get_admin_url($blog_id, '', 'http') . '">' . __('Visit your newly upgraded site &raquo;', 'psts') . '</a></p>';
            return $content;
        }
        if ($customer_id = $this->get_customer_id($blog_id)) {
            try {
                $customer_object = Stripe_Customer::retrieve($customer_id);
            } catch (Exception $e) {
                $error = $e->getMessage();
            }
            $content .= '<div id="psts_existing_info">';
            $end_date = date_i18n(get_option('date_format'), $psts->get_expire($blog_id));
            $level = $psts->get_level_setting($psts->get_level($blog_id), 'name');
            try {
                $invoice_object = Stripe_Invoice::upcoming(array("customer" => $customer_id));
            } catch (Exception $e) {
                $cancel_status = 1;
            }
            try {
                $existing_invoice_object = Stripe_Invoice::all(array("customer" => $customer_id, "count" => 1));
            } catch (Exception $e) {
                $error = $e->getMessage();
            }
            if ($cancel_status == 1) {
                $content .= '<h3>' . __('Your subscription has been canceled', 'psts') . '</h3>';
                $content .= '<p>' . sprintf(__('This site should continue to have %1$s features until %2$s.', 'psts'), $psts->get_setting('rebrand'), $end_date) . '</p>';
            }
            if ($cancel_status == 0) {
                $content .= '<ul>';
                if (is_pro_site($blog_id)) {
                    $content .= '<li>' . __('Level:', 'psts') . ' <strong>' . $level . '</strong></li>';
                }
                if (isset($customer_object->active_card)) {
                    $content .= '<li>' . __('Payment Method: <strong>' . $customer_object->active_card->type . ' Card</strong> ending in <strong>' . $customer_object->active_card->last4 . '</strong>. Expires <strong>' . $customer_object->active_card->exp_month . '/' . $customer_object->active_card->exp_year . '</strong>', 'psts') . '</li>';
                }
                if (isset($exitsing_invoice_object->data[0])) {
                    $content .= '<li>' . __('Last Payment Date:', 'psts') . ' <strong>' . date_i18n(get_option('date_format'), $existing_invoice_object->data[0]->date) . '</strong></li>';
                }
                if (isset($invoice_object->next_payment_attempt)) {
                    $content .= '<li>' . __('Next Payment Date:', 'psts') . ' <strong>' . date_i18n(get_option('date_format'), $invoice_object->next_payment_attempt) . '</strong></li>';
                }
                $content .= "</ul>";
                $cancel_content .= '<h3>' . __('Cancel Your Subscription', 'psts') . '</h3>';
                $pp_active = false;
                if (is_pro_site($blog_id)) {
                    $cancel_content .= '<p>' . sprintf(__('If you choose to cancel your subscription this site should continue to have %1$s features until %2$s.', 'psts'), $level, $end_date) . '</p>';
                    $cancel_content .= '<p><a id="stripe_cancel" href="' . wp_nonce_url($psts->checkout_url($blog_id) . '&action=cancel', 'psts-cancel') . '" title="' . __('Cancel Your Subscription', 'psts') . '"><img src="' . $img_base . 'cancel_subscribe_gen.gif" /></a></p>';
                    $pp_active = true;
                }
                //print receipt send form
                $content .= $psts->receipt_form($blog_id);
                if (!defined('PSTS_CANCEL_LAST')) {
                    $content .= $cancel_content;
                }
                $content .= "<br>";
                $content .= '</div>';
            }
        }
        if (!$cancel_status && is_pro_site($blog_id) && !is_pro_trial($blog_id)) {
            $content .= '<h2>' . __('Change Your Plan or Payment Details', 'psts') . '</h2>
        <p>' . __('You can modify or upgrade your plan or just change your payment method or information below. Your new subscription will automatically go into effect when your next payment is due.', 'psts') . '</p>';
        } else {
            if (!is_pro_site($blog_id) || is_pro_trial($blog_id)) {
                $content .= '<p>' . __('Please choose your desired plan then click the checkout button below.', 'psts') . '</p>';
            }
        }
        $content .= '<form action="' . $psts->checkout_url($blog_id) . '" method="post" autocomplete="off"  id="payment-form">';
        //print the checkout grid
        $content .= $psts->checkout_grid($blog_id);
        $content .= '<div id="psts-stripe-checkout">
			<h2>' . __('Checkout With a Credit Card:', 'psts') . '</h2>';
        $content .= '<div id="psts-processcard-error"></div>';
        $content .= '
				<table id="psts-cc-table">
				<tbody>
				<!-- Credit Card Type -->
				<tr>
				<td class="pypl_label" align="right">' . __('Cardholder Name:', 'psts') . '&nbsp;</td><td>';
        if ($errmsg = $psts->errors->get_error_message('name')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<input id="cc_name" type="text" class="cctext card-first-name" value="" size="25" /> </td>
				</tr>
					<tr>
					<td class="pypl_label" align="right">' . __('Card Number:', 'psts') . '&nbsp;</td>
					<td>';
        if ($errmsg = $psts->errors->get_error_message('number')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<input id="cc_number" type="text" class="cctext card-number" value="" size="23" /><br /><img src="' . $img_base . 'stripe-cards.png" />
					</td>
					</tr>

					<tr>
					<td class="pypl_label" align="right">' . __('Expiration Date:', 'psts') . '&nbsp;</td>
					<td valign="middle">';
        if ($errmsg = $psts->errors->get_error_message('expiration')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<select id="cc_month" class="card-expiry-month">' . $this->month_dropdown() . '</select>&nbsp;/&nbsp;<select id="cc_year" class="card-expiry-year">' . $this->year_dropdown() . '</select>
					</td>
					</tr>

					<!-- Card Security Code -->
					<tr>
						<td class="pypl_label" align="right"><nobr>' . __('Card Security Code:', 'psts') . '</nobr>&nbsp;</td>
						<td valign="middle">';
        if ($errmsg = $psts->errors->get_error_message('cvv2')) {
            $content .= '<div class="psts-error">' . $errmsg . '</div>';
        }
        $content .= '<label><input id="cc_cvv2" size="5" maxlength="4" type="password" class="cctext card-cvc" title="' . __('Please enter a valid card security code. This is the 3 digits on the signature panel, or 4 digits on the front of Amex cards.', 'psts') . '" />
						<img src="' . $img_base . 'buy-cvv.gif" height="27" width="42" title="' . __('Please enter a valid card security code. This is the 3 digits on the signature panel, or 4 digits on the front of Amex cards.', 'psts') . '" /></label>
						</td>
					</tr>
				

				</table>
				</tbody></table>
				<input type="hidden" name="cc_checkout" value="1" />
			<p>
				<input type="submit" id="cc_checkout" name="stripe_checkout_button" value="' . __('Subscribe', 'psts') . ' &raquo;" class="submit-button"/>
				<span id="stripe_processing" style="display: none;float: right;"><img src="' . $img_base . 'loading.gif" /> ' . __('Processing...', 'psts') . '</span>
			</p>
			</div>';
        $content .= '</form>';
        if (defined('PSTS_CANCEL_LAST')) {
            $content .= $cancel_content;
        }
        return $content;
    }
Esempio n. 5
0
	/**
	 * Checks if a given blog is allowed trial status
	 *
	 * @since 3.4.4
	 *
	 * @param int $blog_id
	 *
	 * @return bool
	 */

	function is_trial_allowed( $blog_id ) {
		$trial_days = $this->get_setting( 'trial_days', 0 );

		if ( $trial_days == 0 ) {
			return false;
		}

		// If blog exists
		if( ! empty( $blog_id ) ) {
			if ( is_pro_site( $blog_id ) && ! is_pro_trial( $blog_id ) ) {
				return false;
			}

			if ( $this->is_blog_canceled( $blog_id ) ) {
				return false;
			}
		}

		return true;
	}
 function process_checkout($blog_id)
 {
     global $current_site, $current_user, $psts, $wpdb;
     //add scripts
     add_action('wp_head', array(&$this, 'checkout_js'));
     wp_enqueue_script(array('jquery'));
     //process paypal express checkout
     if (isset($_POST['pypl_checkout_x']) || isset($_POST['pypl_checkout'])) {
         //check for level
         if (empty($_POST['period']) || empty($_POST['level'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return;
         }
         //prepare vars
         $discountAmt = false;
         if ($_POST['period'] == 1) {
             $paymentAmount = $psts->get_level_setting($_POST['level'], 'price_1');
             if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_POST['level'])) {
                 $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                 $discountAmt = $coupon_value['new_total'];
                 $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first month, then %2$s each month', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
             } else {
                 $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s each month', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
             }
         } else {
             if ($_POST['period'] == 3) {
                 $paymentAmount = $psts->get_level_setting($_POST['level'], 'price_3');
                 if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_POST['level'])) {
                     $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                     $discountAmt = $coupon_value['new_total'];
                     $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first 3 month period, then %2$s every 3 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
                 } else {
                     $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every 3 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
                 }
             } else {
                 if ($_POST['period'] == 12) {
                     $paymentAmount = $psts->get_level_setting($_POST['level'], 'price_12');
                     if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_POST['level'])) {
                         $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                         $discountAmt = $coupon_value['new_total'];
                         $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first 12 month period, then %2$s every 12 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
                     } else {
                         $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every 12 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
                     }
                 }
             }
         }
         $desc = apply_filters('psts_pypl_checkout_desc', $desc, $_POST['period'], $_POST['level'], $paymentAmount, $discountAmt, $blog_id);
         $resArray = $this->SetExpressCheckout($paymentAmount, $desc, $blog_id);
         if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
             $token = $resArray["TOKEN"];
             $_SESSION['TOKEN'] = $token;
             $_SESSION['PERIOD'] = $_POST['period'];
             $_SESSION['LEVEL'] = $_POST['level'];
             $this->RedirectToPayPal($token);
         } else {
             $psts->errors->add('paypal', sprintf(__('There was a problem setting up the paypal payment:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), $this->parse_error_string($resArray)));
         }
     }
     /* ------------------- PayPal Checkout ----------------- */
     //check for return from Express Checkout
     if (isset($_GET['token']) && isset($_GET['PayerID']) && isset($_SESSION['PERIOD']) && isset($_SESSION['LEVEL'])) {
         //prepare vars
         $discountAmt = false;
         if ($_SESSION['PERIOD'] == 1) {
             $paymentAmount = $psts->get_level_setting($_SESSION['LEVEL'], 'price_1');
             if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_SESSION['LEVEL'])) {
                 $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                 $discountAmt = $coupon_value['new_total'];
                 $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_SESSION['LEVEL'], 'name') . ': ' . sprintf(__('%1$s for the first month, then %2$s each month', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
             } else {
                 $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_SESSION['LEVEL'], 'name') . ': ' . sprintf(__('%1$s %2$s each month', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
             }
         } else {
             if ($_SESSION['PERIOD'] == 3) {
                 $paymentAmount = $psts->get_level_setting($_SESSION['LEVEL'], 'price_3');
                 if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_SESSION['LEVEL'])) {
                     $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                     $discountAmt = $coupon_value['new_total'];
                     $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_SESSION['LEVEL'], 'name') . ': ' . sprintf(__('%1$s for the first 3 month period, then %2$s every 3 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
                 } else {
                     $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_SESSION['LEVEL'], 'name') . ': ' . sprintf(__('%1$s %2$s every 3 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
                 }
             } else {
                 if ($_SESSION['PERIOD'] == 12) {
                     $paymentAmount = $psts->get_level_setting($_SESSION['LEVEL'], 'price_12');
                     if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_SESSION['LEVEL'])) {
                         $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                         $discountAmt = $coupon_value['new_total'];
                         $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_SESSION['LEVEL'], 'name') . ': ' . sprintf(__('%1$s for the first 12 month period, then %2$s every 12 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
                     } else {
                         $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_SESSION['LEVEL'], 'name') . ': ' . sprintf(__('%1$s %2$s every 12 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
                     }
                 }
             }
         }
         $desc = apply_filters('psts_pypl_checkout_desc', $desc, $_SESSION['PERIOD'], $_SESSION['LEVEL'], $paymentAmount, $discountAmt, $blog_id);
         //get coupon payment amount
         if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_SESSION['LEVEL'])) {
             $coupon = true;
             $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
             $initAmount = $coupon_value['new_total'];
         } else {
             $coupon = false;
             $initAmount = $paymentAmount;
         }
         //check for modifiying
         if (is_pro_site($blog_id) && !is_pro_trial($blog_id)) {
             $modify = $psts->get_expire($blog_id);
             //check for a upgrade and get new first payment date
             if ($upgrade = $psts->calc_upgrade($blog_id, $initAmount, $_SESSION['LEVEL'], $_SESSION['PERIOD'])) {
                 $modify = $upgrade;
             } else {
                 $upgrade = false;
             }
         } else {
             $modify = false;
         }
         if ($modify) {
             //create the recurring profile
             $resArray = $this->CreateRecurringPaymentsProfileExpress($_GET['token'], $paymentAmount, $_SESSION['PERIOD'], $desc, $blog_id, $_SESSION['LEVEL'], $modify);
             if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                 $new_profile_id = $resArray["PROFILEID"];
                 $end_date = date_i18n(get_blog_option($blog_id, 'date_format'), $modify);
                 $psts->log_action($blog_id, sprintf(__('User modifying subscription via PayPal Express: New subscription created (%1$s), first payment will be made on %2$s - %3$s', 'psts'), $desc, $end_date, $new_profile_id));
                 //cancel old subscription
                 $old_gateway = $wpdb->get_var("SELECT gateway FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = '{$blog_id}'");
                 if ($profile_id = $this->get_profile_id($blog_id)) {
                     $resArray = $this->ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %1$s subscription has been modified. This previous subscription has been canceled, and your new subscription (%2$s) will begin on %3$s.', 'psts'), $psts->get_setting('rebrand'), $desc, $end_date));
                     if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                         $psts->log_action($blog_id, sprintf(__('User modifying subscription via PayPal Express: Old subscription canceled - %s', 'psts'), $profile_id));
                     }
                 } else {
                     $this->manual_cancel_email($blog_id, $old_gateway);
                     //send email for old paypal system
                 }
                 //change expiration if upgrading
                 if ($_SESSION['LEVEL'] > ($old_level = $psts->get_level($blog_id))) {
                     $expire_sql = $upgrade ? " expire = '{$upgrade}'," : '';
                     $wpdb->query($wpdb->prepare("UPDATE {$wpdb->base_prefix}pro_sites SET{$expire_sql} level = %d, term = %d WHERE blog_ID = %d", $_SESSION['LEVEL'], $_SESSION['PERIOD'], $blog_id));
                     unset($psts->level[$blog_id]);
                     //clear cache
                     $psts->log_action($blog_id, sprintf(__('Pro Site level upgraded from "%s" to "%s".', 'psts'), $psts->get_level_setting($old_level, 'name'), $psts->get_level_setting($_SESSION['LEVEL'], 'name')));
                     do_action('psts_upgrade', $blog_id, $_SESSION['LEVEL'], $old_level);
                     $psts->record_stat($blog_id, 'upgrade');
                 } else {
                     $psts->record_stat($blog_id, 'modify');
                 }
                 //use coupon
                 if ($coupon) {
                     $psts->use_coupon($_SESSION['COUPON_CODE'], $blog_id);
                 }
                 //save new profile_id
                 $this->set_profile_id($blog_id, $new_profile_id);
                 //save new period/term
                 $wpdb->query($wpdb->prepare("UPDATE {$wpdb->base_prefix}pro_sites SET term = %d WHERE blog_ID = %d", $_SESSION['PERIOD'], $blog_id));
                 //show confirmation page
                 $this->complete_message = sprintf(__('Your PayPal subscription modification was successful for %s.', 'psts'), $desc);
                 //display GA ecommerce in footer
                 $psts->create_ga_ecommerce($blog_id, $_SESSION['PERIOD'], $initAmount, $_SESSION['LEVEL']);
                 //show instructions for old gateways
                 if ($old_gateway == 'PayPal') {
                     $this->complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your PayPal account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                     $this->complete_message .= '<p><a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_subscr-find&alias=' . urlencode(get_site_option("supporter_paypal_email")) . '"><img src="' . $psts->plugin_url . 'images/cancel_subscribe_gen.gif" /></a><br /><small>' . __('You can also cancel following <a href="https://www.paypal.com/webapps/helpcenter/article/?articleID=94044#canceling_recurring_paymemt_subscription_automatic_billing">these steps</a>.', 'psts') . '</small></p>';
                 } else {
                     if ($old_gateway == 'Amazon') {
                         $this->complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your Amazon Payments account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                         $this->complete_message .= '<p>' . __('To view your subscriptions, simply go to <a target="_blank" href="https://payments.amazon.com/">https://payments.amazon.com/</a>, click Your Account at the top of the page, log in to your Amazon Payments account (if asked), and then click the Your Subscriptions link. This page displays your subscriptions, showing the most recent, active subscription at the top. To view the details of a specific subscription, click Details. Then cancel your subscription by clicking the Cancel Subscription button on the Subscription Details page.', 'psts') . '</p>';
                     }
                 }
                 unset($_SESSION['COUPON_CODE']);
                 unset($_SESSION['PERIOD']);
                 unset($_SESSION['LEVEL']);
             } else {
                 $psts->errors->add('general', sprintf(__('There was a problem setting up the Paypal payment:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), $this->parse_error_string($resArray)));
                 $psts->log_action($blog_id, sprintf(__('User modifying subscription via PayPal Express: PayPal returned an error: %s', 'psts'), $this->parse_error_string($resArray)));
             }
         } else {
             //new or expired signup
             $resArray = $this->DoExpressCheckoutPayment($_GET['token'], $_GET['PayerID'], $paymentAmount, $_SESSION['PERIOD'], $desc, $blog_id, $_SESSION['LEVEL']);
             if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                 //get result
                 $payment_status = $resArray['PAYMENTSTATUS'];
                 $amount = $resArray['AMT'];
                 $init_transaction = $resArray['TRANSACTIONID'];
                 $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Initial payment successful (%1$s) - Transaction ID: %2$s', 'psts'), $desc, $init_transaction));
                 //use coupon
                 if ($coupon) {
                     $psts->use_coupon($_SESSION['COUPON_CODE'], $blog_id);
                 }
                 //just in case, try to cancel any old subscription
                 if ($profile_id = $this->get_profile_id($blog_id)) {
                     $resArray = $this->ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %s subscription has been modified. This previous subscription has been canceled.', 'psts'), $psts->get_setting('rebrand')));
                 }
                 //create the recurring profile
                 $resArray = $this->CreateRecurringPaymentsProfileExpress($_GET['token'], $paymentAmount, $_SESSION['PERIOD'], $desc, $blog_id, $_SESSION['LEVEL']);
                 if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                     //save new profile_id
                     $this->set_profile_id($blog_id, $resArray["PROFILEID"]);
                     $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]));
                 } else {
                     $this->complete_message = __('Your initial PayPal transaction was successful, but there was a problem creating the subscription so you may need to renew when the first period is up. Your site should be upgraded shortly.', 'psts') . '<br />"<strong>' . $this->parse_error_string($resArray) . '</strong>"';
                     $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: Problem creating the subscription after successful initial payment. User may need to renew when the first period is up: %s', 'psts'), $this->parse_error_string($resArray)));
                 }
                 //now get the details of the transaction to see if initial payment went through already
                 if ($payment_status == 'Completed' || $payment_status == 'Processed') {
                     $psts->extend($blog_id, $_SESSION['PERIOD'], 'PayPal Express/Pro', $_SESSION['LEVEL'], $paymentAmount);
                     $psts->record_stat($blog_id, 'signup');
                     $psts->email_notification($blog_id, 'success');
                     //record last payment
                     $psts->record_transaction($blog_id, $init_transaction, $amount);
                     // Added for affiliate system link
                     do_action('supporter_payment_processed', $blog_id, $amount, $_SESSION['PERIOD'], $_SESSION['LEVEL']);
                     if (empty($this->complete_message)) {
                         $this->complete_message = __('Your PayPal subscription was successful! You should be receiving an email receipt shortly.', 'psts');
                     }
                 } else {
                     update_blog_option($blog_id, 'psts_waiting_step', 1);
                 }
                 //display GA ecommerce in footer
                 $psts->create_ga_ecommerce($blog_id, $_SESSION['PERIOD'], $amount, $_SESSION['LEVEL']);
                 unset($_SESSION['COUPON_CODE']);
                 unset($_SESSION['PERIOD']);
                 unset($_SESSION['LEVEL']);
             } else {
                 $psts->errors->add('general', sprintf(__('There was a problem setting up the Paypal payment:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), $this->parse_error_string($resArray)));
                 $psts->log_action($blog_id, sprintf(__('User creating new subscription via PayPal Express: PayPal returned an error: %s', 'psts'), $this->parse_error_string($resArray)));
             }
         }
     }
     /* ------------ CC Checkout ----------------- */
     if (isset($_POST['cc_checkout'])) {
         //check for level
         if (empty($_POST['period']) || empty($_POST['level'])) {
             $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts'));
             return;
         }
         //process form
         if (isset($_POST['cc_form'])) {
             //clean up $_POST
             $cc_cardtype = isset($_POST['cc_card-type']) ? $_POST['cc_card-type'] : '';
             $cc_number = isset($_POST['cc_number']) ? stripslashes($_POST['cc_number']) : '';
             $cc_month = isset($_POST['cc_month']) ? $_POST['cc_month'] : '';
             $cc_year = isset($_POST['cc_year']) ? $_POST['cc_year'] : '';
             $cc_firstname = isset($_POST['cc_firstname']) ? stripslashes($_POST['cc_firstname']) : '';
             $cc_lastname = isset($_POST['cc_lastname']) ? stripslashes($_POST['cc_lastname']) : '';
             $cc_address = isset($_POST['cc_address']) ? stripslashes($_POST['cc_address']) : '';
             $cc_address2 = isset($_POST['cc_address2']) ? stripslashes($_POST['cc_address2']) : '';
             $cc_city = isset($_POST['cc_city']) ? stripslashes($_POST['cc_city']) : '';
             $cc_state = isset($_POST['cc_state']) ? stripslashes($_POST['cc_state']) : '';
             $cc_zip = isset($_POST['cc_zip']) ? stripslashes($_POST['cc_zip']) : '';
             $cc_country = isset($_POST['cc_country']) ? stripslashes($_POST['cc_country']) : '';
             $cc_number = preg_replace('/[^0-9]/', '', $cc_number);
             //strip any slashes
             $_POST['cc_cvv2'] = preg_replace('/[^0-9]/', '', $_POST['cc_cvv2']);
             //check nonce
             if (!$this->check_nonce()) {
                 $psts->errors->add('general', __('Whoops, looks like you may have tried to submit your payment twice so we prevented it. Check your subscription info below to see if it was created. If not, please try again.', 'psts'));
             }
             if (empty($cc_cardtype)) {
                 $psts->errors->add('card-type', __('Please choose a Card Type.', 'psts'));
             }
             if (empty($cc_number)) {
                 $psts->errors->add('number', __('Please enter a valid Credit Card Number.', 'psts'));
             }
             if (empty($cc_month) || empty($cc_year)) {
                 $psts->errors->add('expiration', __('Please choose an expiration date.', 'psts'));
             }
             if (strlen($_POST['cc_cvv2']) < 3 || strlen($_POST['cc_cvv2']) > 4) {
                 $psts->errors->add('cvv2', __('Please enter a valid card security code. This is the 3 digits on the signature panel, or 4 digits on the front of Amex cards.', 'psts'));
             }
             if (empty($cc_firstname)) {
                 $psts->errors->add('firstname', __('Please enter your First Name.', 'psts'));
             }
             if (empty($cc_lastname)) {
                 $psts->errors->add('lastname', __('Please enter your Last Name.', 'psts'));
             }
             if (empty($cc_address)) {
                 $psts->errors->add('address', __('Please enter your billing Street Address.', 'psts'));
             }
             if (empty($_POST['cc_city'])) {
                 $psts->errors->add('city', __('Please enter your billing City.', 'psts'));
             }
             if (($cc_country == 'US' || $cc_country == 'CA') && empty($cc_state)) {
                 $psts->errors->add('state', __('Please enter your billing State/Province.', 'psts'));
             }
             if (empty($cc_zip)) {
                 $psts->errors->add('zip', __('Please enter your billing Zip/Postal Code.', 'psts'));
             }
             if (empty($cc_country) || strlen($cc_country) != 2) {
                 $psts->errors->add('country', __('Please enter your billing Country.', 'psts'));
             }
             //no errors
             if (!$psts->errors->get_error_code()) {
                 //prepare vars
                 $discountAmt = false;
                 if ($_POST['period'] == 1) {
                     $paymentAmount = $psts->get_level_setting($_POST['level'], 'price_1');
                     if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_POST['level'])) {
                         $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                         $discountAmt = $coupon_value['new_total'];
                         $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first month, then %2$s each month', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
                     } else {
                         $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s each month', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
                     }
                 } else {
                     if ($_POST['period'] == 3) {
                         $paymentAmount = $psts->get_level_setting($_POST['level'], 'price_3');
                         if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_POST['level'])) {
                             $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                             $discountAmt = $coupon_value['new_total'];
                             $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first 3 month period, then %2$s every 3 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
                         } else {
                             $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every 3 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
                         }
                     } else {
                         if ($_POST['period'] == 12) {
                             $paymentAmount = $psts->get_level_setting($_POST['level'], 'price_12');
                             if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_POST['level'])) {
                                 $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                                 $discountAmt = $coupon_value['new_total'];
                                 $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first 12 month period, then %2$s every 12 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $discountAmt), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount));
                             } else {
                                 $desc = $current_site->site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every 12 months', 'psts'), $psts->format_currency($psts->get_setting('pypl_currency'), $paymentAmount), $psts->get_setting('pypl_currency'));
                             }
                         }
                     }
                 }
                 $desc = apply_filters('psts_pypl_checkout_desc', $desc, $_POST['period'], $_POST['level'], $paymentAmount, $discountAmt, $blog_id);
                 //get coupon payment amount
                 if (isset($_SESSION['COUPON_CODE']) && $psts->check_coupon($_SESSION['COUPON_CODE'], $blog_id, $_SESSION['LEVEL'])) {
                     $coupon = true;
                     $coupon_value = $psts->coupon_value($_SESSION['COUPON_CODE'], $paymentAmount);
                     $initAmount = $coupon_value['new_total'];
                 } else {
                     $coupon = false;
                     $initAmount = $paymentAmount;
                 }
                 //check for modifiying
                 if (is_pro_site($blog_id) && !is_pro_trial($blog_id)) {
                     $modify = $psts->get_expire($blog_id);
                     //check for a upgrade and get new first payment date
                     if ($upgrade = $psts->calc_upgrade($blog_id, $initAmount, $_SESSION['LEVEL'], $_SESSION['PERIOD'])) {
                         $modify = $upgrade;
                     } else {
                         $upgrade = false;
                     }
                 } else {
                     $modify = false;
                 }
                 if ($modify) {
                     //create the recurring profile
                     $resArray = $this->CreateRecurringPaymentsProfileDirect($paymentAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $cc_cardtype, $cc_number, $cc_month . $cc_year, $_POST['cc_cvv2'], $cc_firstname, $cc_lastname, $cc_address, $cc_address2, $cc_city, $cc_state, $cc_zip, $cc_country, $current_user->user_email, $modify);
                     if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                         $new_profile_id = $resArray["PROFILEID"];
                         $end_date = date_i18n(get_blog_option($blog_id, 'date_format'), $modify);
                         $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: New subscription created (%1$s), first payment will be made on %2$s - %3$s', 'psts'), $desc, $end_date, $new_profile_id));
                         //cancel old subscription
                         $old_gateway = $wpdb->get_var("SELECT gateway FROM {$wpdb->base_prefix}pro_sites WHERE blog_ID = '{$blog_id}'");
                         if ($profile_id = $this->get_profile_id($blog_id)) {
                             $resArray = $this->ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %1$s subscription has been modified. This previous subscription has been canceled, and your new subscription (%2$s) will begin on %3$s.', 'psts'), $psts->get_setting('rebrand'), $desc, $end_date));
                             if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                                 $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: Old subscription canceled - %s', 'psts'), $profile_id));
                             }
                         } else {
                             $this->manual_cancel_email($blog_id, $old_gateway);
                             //send email for old paypal system
                         }
                         //change expiration if upgrading
                         if ($_POST['level'] > ($old_level = $psts->get_level($blog_id))) {
                             $expire_sql = $upgrade ? " expire = '{$upgrade}'," : '';
                             $wpdb->query($wpdb->prepare("UPDATE {$wpdb->base_prefix}pro_sites SET{$expire_sql} level = %d, term = %d WHERE blog_ID = %d", $_POST['level'], $_POST['period'], $blog_id));
                             unset($psts->level[$blog_id]);
                             //clear cache
                             $psts->log_action($blog_id, sprintf(__('Pro Site level upgraded from "%s" to "%s".', 'psts'), $psts->get_level_setting($old_level, 'name'), $psts->get_level_setting($_POST['level'], 'name')));
                             do_action('psts_upgrade', $blog_id, $_POST['level'], $old_level);
                             $psts->record_stat($blog_id, 'upgrade');
                         } else {
                             $psts->record_stat($blog_id, 'modify');
                         }
                         //use coupon
                         if ($coupon) {
                             $psts->use_coupon($_SESSION['COUPON_CODE'], $blog_id);
                         }
                         //save new profile_id
                         $this->set_profile_id($blog_id, $new_profile_id);
                         //save new period/term
                         $wpdb->query($wpdb->prepare("UPDATE {$wpdb->base_prefix}pro_sites SET term = %d WHERE blog_ID = %d", $_POST['period'], $blog_id));
                         //show confirmation page
                         $this->complete_message = sprintf(__('Your Credit Card subscription modification was successful for %s.', 'psts'), $desc);
                         //display GA ecommerce in footer
                         $psts->create_ga_ecommerce($blog_id, $_POST['period'], $initAmount, $_POST['level'], $cc_city, $cc_state, $cc_country);
                         //show instructions for old gateways
                         if ($old_gateway == 'PayPal') {
                             $this->complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your PayPal account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                             $this->complete_message .= '<p><a target="_blank" href="https://www.paypal.com/cgi-bin/webscr?cmd=_subscr-find&alias=' . urlencode(get_site_option("supporter_paypal_email")) . '"><img src="' . $psts->plugin_url . 'images/cancel_subscribe_gen.gif" /></a><br /><small>' . __('You can also cancel following <a href="https://www.paypal.com/helpcenter/main.jsp;jsessionid=SCPbTbhRxL6QvdDMvshNZ4wT2DH25d01xJHj6cBvNJPGFVkcl6vV!795521328?t=solutionTab&ft=homeTab&ps=&solutionId=27715&locale=en_US&_dyncharset=UTF-8&countrycode=US&cmd=_help-ext">these steps</a>.', 'psts') . '</small></p>';
                         } else {
                             if ($old_gateway == 'Amazon') {
                                 $this->complete_message .= '<p><strong>' . __('Because of billing system upgrades, we were unable to cancel your old subscription automatically, so it is important that you cancel the old one yourself in your Amazon Payments account, otherwise the old payments will continue along with new ones! Note this is the only time you will have to do this.', 'psts') . '</strong></p>';
                                 $this->complete_message .= '<p>' . __('To view your subscriptions, simply go to <a target="_blank" href="https://payments.amazon.com/">https://payments.amazon.com/</a>, click Your Account at the top of the page, log in to your Amazon Payments account (if asked), and then click the Your Subscriptions link. This page displays your subscriptions, showing the most recent, active subscription at the top. To view the details of a specific subscription, click Details. Then cancel your subscription by clicking the Cancel Subscription button on the Subscription Details page.', 'psts') . '</p>';
                             }
                         }
                         unset($_SESSION['COUPON_CODE']);
                     } else {
                         $psts->errors->add('general', sprintf(__('There was a problem with your Credit Card information:<br />"<strong>%s</strong>"<br />Please try again.', 'psts'), $this->parse_error_string($resArray)));
                         $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: PayPal returned a problem with Credit Card info: %s', 'psts'), $this->parse_error_string($resArray)));
                     }
                 } else {
                     //new or expired signup
                     //attempt initial direct payment
                     $resArray = $this->DoDirectPayment($paymentAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $cc_cardtype, $cc_number, $cc_month . $cc_year, $_POST['cc_cvv2'], $cc_firstname, $cc_lastname, $cc_address, $cc_address2, $cc_city, $cc_state, $cc_zip, $cc_country, $current_user->user_email);
                     if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                         $init_transaction = $resArray["TRANSACTIONID"];
                         //just in case, try to cancel any old subscription
                         if ($profile_id = $this->get_profile_id($blog_id)) {
                             $resArray = $this->ManageRecurringPaymentsProfileStatus($profile_id, 'Cancel', sprintf(__('Your %s subscription has been modified. This previous subscription has been canceled.', 'psts'), $psts->get_setting('rebrand')));
                         }
                         $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Initial payment successful (%1$s) - Transaction ID: %2$s', 'psts'), $desc, $init_transaction));
                         //use coupon
                         if ($coupon) {
                             $psts->use_coupon($_SESSION['COUPON_CODE'], $blog_id);
                         }
                         //now attempt to create the subscription
                         $resArray = $this->CreateRecurringPaymentsProfileDirect($paymentAmount, $_POST['period'], $desc, $blog_id, $_POST['level'], $cc_cardtype, $cc_number, $cc_month . $cc_year, $_POST['cc_cvv2'], $cc_firstname, $cc_lastname, $cc_address, $cc_address2, $cc_city, $cc_state, $cc_zip, $cc_country, $current_user->user_email);
                         if ($resArray['ACK'] == 'Success' || $resArray['ACK'] == 'SuccessWithWarning') {
                             //save new profile_id
                             $this->set_profile_id($blog_id, $resArray["PROFILEID"]);
                             $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Profile ID: %2$s', 'psts'), $desc, $resArray["PROFILEID"]));
                         } else {
                             $this->complete_message = __('Your initial payment was successful, but there was a problem creating the subscription with your credit card so you may need to renew when the first period is up. Your site should be upgraded shortly.', 'psts') . '<br />"<strong>' . $this->parse_error_string($resArray) . '</strong>"';
                             $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Problem creating the subscription after successful initial payment. User may need to renew when the first period is up: %s', 'psts'), $this->parse_error_string($resArray)));
                         }
                         //now get the details of the transaction to see if initial payment went through
                         $result = $this->GetTransactionDetails($init_transaction);
                         if ($result['PAYMENTSTATUS'] == 'Completed' || $result['PAYMENTSTATUS'] == 'Processed') {
                             $psts->extend($blog_id, $_POST['period'], 'PayPal Express/Pro', $_POST['level'], $paymentAmount);
                             $psts->record_stat($blog_id, 'signup');
                             $psts->email_notification($blog_id, 'success');
                             //record last payment
                             $psts->record_transaction($blog_id, $init_transaction, $result['AMT']);
                             // Added for affiliate system link
                             do_action('supporter_payment_processed', $blog_id, $result['AMT'], $_POST['period'], $_POST['level']);
                             if (empty($this->complete_message)) {
                                 $this->complete_message = sprintf(__('Your Credit Card subscription was successful! You should be receiving an email receipt at %s shortly.', 'psts'), get_blog_option($blog_id, 'admin_email'));
                             }
                         } else {
                             update_blog_option($blog_id, 'psts_waiting_step', 1);
                         }
                         //display GA ecommerce in footer
                         $psts->create_ga_ecommerce($blog_id, $_POST['period'], $initAmount, $_POST['level'], $cc_city, $cc_state, $cc_country);
                         unset($_SESSION['COUPON_CODE']);
                     } else {
                         $psts->errors->add('general', sprintf(__('There was a problem with your credit card information:<br />"<strong>%s</strong>"<br />Please check all fields and try again.', 'psts'), $this->parse_error_string($resArray)));
                     }
                 }
             } else {
                 $psts->errors->add('general', __('There was a problem with your credit card information. Please check all fields and try again.', 'psts'));
             }
         }
     }
 }
Esempio n. 7
0
    function embi_prosites_section($title = '')
    {
        global $wpdb, $psts;
        if (!current_user_can('manage_options')) {
            if (!function_exists('is_pro_user')) {
                return;
            }
        }
        // If not a Pro User (whatever that is). Then we do not show the Pro Site section
        if (!is_pro_user(get_current_user_id())) {
            return;
        }
        $levels = (array) get_site_option('psts_levels');
        $site_level = $psts->get_level($wpdb->blogid);
        if (isset($levels[intval($site_level)])) {
            $site_level_text = $levels[intval($site_level)]['name'];
        } else {
            $site_level_text = '<a class="button button-primary" href="' . admin_url('admin.php?page=psts-checkout') . '">' . __('Upgrade to Pro!', 'embi') . '</a>';
        }
        if (is_pro_trial($wpdb->blogid)) {
            $site_level_text .= " (Trial)" . ' <a style="float: right" class="button button-primary" href="' . admin_url('admin.php?page=psts-checkout') . '">' . __('Upgrade to Pro!', 'embi') . '</a>';
        }
        $site_expire = $psts->get_expire($wpdb->blogid);
        //echo "site_expire=[". $site_expire ."]<br />";
        //$site_expire_text = '<strong>'. __('Expired', 'embi'). '</strong>';
        if (empty($site_expire)) {
            $site_expire_text = '';
        } else {
            if ($site_expire > 2147483647) {
                $site_expire_text = __('<strong>Never</strong>', 'embi');
            } else {
                $site_expire_text = date_i18n(get_option('date_format'), $site_expire) . " (" . intval(($site_expire - time()) / 86400) . " " . __('days', 'embi') . ")";
            }
        }
        ?>
		<div class="embi-rightnow-wrapper embi-rightnow-my-blogs-section">
			<div class="embi_dashboard">
				<h4 class="embi-section-title"><?php 
        echo $title;
        ?>
<a 
					style="float:right" href="<?php 
        echo admin_url('admin.php?page=psts-checkout');
        ?>
"><?php 
        _e('Manage Pro Account', 'embi');
        ?>
</a></h4>
				<ul>	
					<li>
						<div class="embi-item_title"><?php 
        _e('Level');
        ?>
:</div>
						<div class="embi-item_value"><?php 
        echo $site_level_text;
        ?>
</div>
					</li>
					<?php 
        if (!empty($site_expire_text)) {
            ?>
					<li>
						<div class="embi-item_title"><?php 
            _e('Expiration date');
            ?>
:</div>
						<div class="embi-item_value"><?php 
            echo $site_expire_text;
            ?>
</div>
					</li>
					<?php 
        }
        ?>
				</ul>
			</div>
		</div>
		<?php 
    }