Beispiel #1
1
 /**
  * Create and send the request
  * 
  * @param array $options array of options to be send in POST request
  * @return gateway_response response object
  * 
  */
 public function send($options, $type = '')
 {
     $result = '';
     try {
         if ($type == 'subscription') {
             $result = Stripe_Customer::create($options);
         } elseif ($type == 'plan') {
             $result = Stripe_Plan::create($options);
         } elseif ($type == 'retrieve') {
             $result = Stripe_Plan::retrieve($options);
         } elseif ($type == 'customer') {
             $result = Stripe_Customer::create($options);
         } elseif ($type == 'invoice') {
             $result = Stripe_InvoiceItem::create($options);
             // Stripe_Customer::invoiceItems($options);
         } elseif ($type == 'cancel') {
             $cu = Stripe_Customer::retrieve($options['customer']);
             $result = $cu->cancelSubscription();
         } else {
             $result = Stripe_Charge::create($options);
         }
     } catch (Exception $ex) {
         $result = $ex;
     }
     $response = new stripe_response($result);
     return $response;
 }
Beispiel #2
1
/**
 * Create recurring payment plans when downloads are saved
 *
 * This is in order to support the Recurring Payments module
 *
 * @access      public
 * @since       1.5
 * @return      int
 */
function edds_create_recurring_plans($post_id = 0)
{
    global $edd_options, $post;
    if (!class_exists('EDD_Recurring')) {
        return $post_id;
    }
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE || defined('DOING_AJAX') && DOING_AJAX || isset($_REQUEST['bulk_edit'])) {
        return $post_id;
    }
    if (isset($post->post_type) && $post->post_type == 'revision') {
        return $post_id;
    }
    if (!isset($post->post_type) || $post->post_type != 'download') {
        return $post_id;
    }
    if (!current_user_can('edit_products', $post_id)) {
        return $post_id;
    }
    if (!class_exists('Stripe')) {
        require_once EDDS_PLUGIN_DIR . '/Stripe/Stripe.php';
    }
    $secret_key = edd_is_test_mode() ? trim($edd_options['test_secret_key']) : trim($edd_options['live_secret_key']);
    $plans = array();
    try {
        Stripe::setApiKey($secret_key);
        if (edd_has_variable_prices($post_id)) {
            $prices = edd_get_variable_prices($post_id);
            foreach ($prices as $price_id => $price) {
                if (EDD_Recurring()->is_price_recurring($post_id, $price_id)) {
                    $period = EDD_Recurring()->get_period($price_id, $post_id);
                    if ($period == 'day' || $period == 'week') {
                        wp_die(__('Stripe only permits yearly and monthly plans.', 'edds'), __('Error', 'edds'));
                    }
                    if (EDD_Recurring()->get_times($price_id, $post_id) > 0) {
                        wp_die(__('Stripe requires that the Times option be set to 0.', 'edds'), __('Error', 'edds'));
                    }
                    $plans[] = array('name' => $price['name'], 'price' => $price['amount'], 'period' => $period);
                }
            }
        } else {
            if (EDD_Recurring()->is_recurring($post_id)) {
                $period = EDD_Recurring()->get_period_single($post_id);
                if ($period == 'day' || $period == 'week') {
                    wp_die(__('Stripe only permits yearly and monthly plans.', 'edds'), __('Error', 'edds'));
                }
                if (EDD_Recurring()->get_times_single($post_id) > 0) {
                    wp_die(__('Stripe requires that the Times option be set to 0.', 'edds'), __('Error', 'edds'));
                }
                $plans[] = array('name' => get_post_field('post_name', $post_id), 'price' => edd_get_download_price($post_id), 'period' => $period);
            }
        }
        // Get all plans so we know which ones already exist
        $all_plans = array();
        $more = true;
        $params = array('limit' => 100);
        // Plan request params
        while ($more) {
            if (!empty($all_plans)) {
                $params['starting_after'] = end($all_plans);
            }
            $response = Stripe_Plan::all($params);
            $all_plans = array_merge($all_plans, wp_list_pluck($response->data, "id"));
            $more = absint($response->has_more);
        }
        foreach ($plans as $plan) {
            // Create the plan ID
            $plan_id = $plan['name'] . '_' . $plan['price'] . '_' . $plan['period'];
            $plan_id = sanitize_key($plan_id);
            $plan_id = apply_filters('edd_recurring_plan_id', $plan_id, $plan);
            if (in_array($plan_id, $all_plans)) {
                continue;
            }
            if (edds_is_zero_decimal_currency()) {
                $amount = $plan['price'];
            } else {
                $amount = $plan['price'] * 100;
            }
            $plan_args = array("amount" => $amount, "interval" => $plan['period'], "name" => $plan['name'], "currency" => edd_get_currency(), "id" => $plan_id);
            $plan_args = apply_filters('edd_recurring_plan_details', $plan_args, $plan_id);
            Stripe_Plan::create($plan_args);
        }
    } catch (Exception $e) {
        wp_die(__('There was an error creating a payment plan with Stripe.', 'edds'), __('Error', 'edds'));
    }
}
Beispiel #3
0
 public function chargePackage()
 {
     $user = $this->session->userdata('user');
     $customer = Stripe_Customer::retrieve($user->stripe_customer_id);
     try {
         $plan = Stripe_Plan::retrieve($_POST['planId']);
         $this->load->library('stripe_library');
         $subscription_id = $this->stripe_library->get_main_subscription_id($user->stripe_customer_id);
         if ($subscription_id) {
             $subscription = $customer->subscriptions->retrieve($subscription_id);
             $subscription->plan = $_POST['planId'];
             $subscription->card = $_POST['stripeToken'];
             $subscription->save();
         } else {
             $customer->subscriptions->create(array("plan" => $plan->id, "trial_end" => 'now', 'card' => $_POST['stripeToken']));
         }
         $this->data['message'] = "Success";
     } catch (Stripe_CardError $e) {
         $err = $e->getJsonBody()['error'];
         $this->data['message'] = "Error Type: " . $err['code'] . "\n Message: " . $err['message'];
     } catch (Stripe_InvalidRequestError $e) {
         //customer has no active cards
         $err = $e->getJsonBody()['error'];
         $this->data['message'] = "Message: " . $err['message'];
     }
     $this->data['user'] = $user;
     $this->data['packageName'] = $_POST['planName'];
     $this->_renderL('pages/store_success');
 }
function sktest_get_stripe_plans()
{
    global $stripe_options;
    // load the stripe libraries
    if (!class_exists('Stripe')) {
        require_once STRIPE_BASE_DIR . '/lib/Stripe.php';
    }
    // check if we are using test mode
    if (isset($stripe_options['test_mode']) && $stripe_options['test_mode']) {
        $secret_key = $stripe_options['test_secret_key'];
    } else {
        $secret_key = $stripe_options['live_secret_key'];
    }
    Stripe::setApiKey($secret_key);
    // retrieve all plans from stripe
    $plans_data = Stripe_Plan::all();
    // setup a blank array
    $plans = array();
    if ($plans_data) {
        foreach ($plans_data['data'] as $plan) {
            // store the plan ID as the array key and the plan name as the value
            $plans[$plan['id']] = $plan['name'];
        }
    }
    return $plans;
}
Beispiel #5
0
 public function testSave()
 {
     authorizeFromEnv();
     $planId = 'gold-' . self::randomString();
     $p = Stripe_Plan::create(array('amount' => 2000, 'interval' => 'month', 'currency' => 'usd', 'name' => 'Plan', 'id' => $planId));
     $p->name = 'A new plan name';
     $p->save();
     $this->assertEqual($p->name, 'A new plan name');
     $p2 = Stripe_Plan::retrieve($planId);
     $this->assertEqual($p->name, $p2->name);
 }
Beispiel #6
0
 public function read()
 {
     $id = $this->inputfilter->clean($this->app->get('PARAMS.id'), 'alnum');
     $number = $this->inputfilter->clean($this->app->get('PARAMS.number'), 'cmd');
     // these are like slugs, and can have a hyphen in them
     $model = $this->getModel();
     if ($id) {
         $model->setState('filter.id', $id);
     } elseif ($number) {
         $model->setState('filter.number', $number);
     } else {
         \Dsc\System::instance()->addMessage("Invalid Item", 'error');
         $this->app->reroute('/');
     }
     try {
         $subscription = $model->getItem();
         if (empty($subscription->id)) {
             throw new \Exception();
         }
     } catch (\Exception $e) {
         \Dsc\System::instance()->addMessage("Invalid Item", 'error');
         $this->app->reroute('/');
         return;
     }
     $this->app->set('subscription', $subscription);
     if (empty($subscription->subscriber)) {
         $this->app->set('meta.title', $subscription->title);
         $settings = \Striper\Models\Settings::fetch();
         // Set your secret key: remember to change this to your live secret key in production
         // See your keys here https://manage.stripe.com/account
         $this->app->set('plan', \Stripe_Plan::retrieve($subscription->{'plan'}));
         $this->app->set('settings', $settings);
         echo $this->theme->render('Striper/Site/Views::subscription/read.php');
     } else {
         echo $this->theme->render('Striper/Site/Views::subscription/alreadypaid.php');
     }
 }
 /**
  * Get a Stripe plan object instance.
  *
  * @param array $shortcode_attrs An array of shortcode attributes.
  * @param array $metadata Any additional metadata.
  *
  * @return Stripe_Plan|string Plan object; else error message.
  */
 public static function get_plan($shortcode_attrs, $metadata = array())
 {
     $input_time = time();
     // Initialize.
     $input_vars = get_defined_vars();
     // Arguments.
     require_once dirname(__FILE__) . '/stripe-sdk/lib/Stripe.php';
     Stripe::setApiKey($GLOBALS['WS_PLUGIN__']['s2member']['o']['pro_stripe_api_secret_key']);
     $amount = $shortcode_attrs['ra'];
     $currency = $shortcode_attrs['cc'];
     $name = $shortcode_attrs['desc'];
     $metadata['recurring'] = $shortcode_attrs['rr'] && $shortcode_attrs['rr'] !== 'BN';
     $metadata['recurring_times'] = $shortcode_attrs['rr'] && $shortcode_attrs['rrt'] ? (int) $shortcode_attrs['rrt'] : -1;
     $trial_period_days = self::per_term_2_days($shortcode_attrs['tp'], $shortcode_attrs['tt']);
     $interval_days = self::per_term_2_days($shortcode_attrs['rp'], $shortcode_attrs['rt']);
     $plan_id = 's2_' . md5($amount . $currency . $name . $trial_period_days . $interval_days . serialize($metadata) . $GLOBALS['WS_PLUGIN__']['s2member']['o']['pro_stripe_api_statement_description']);
     try {
         try {
             $plan = Stripe_Plan::retrieve($plan_id);
         } catch (exception $exception) {
             $plan = array('id' => $plan_id, 'name' => $name, 'metadata' => $metadata, 'amount' => self::dollar_amount_to_cents($amount, $currency), 'currency' => $currency, 'statement_descriptor' => $GLOBALS['WS_PLUGIN__']['s2member']['o']['pro_stripe_api_statement_description'], 'interval' => 'day', 'interval_count' => $interval_days, 'trial_period_days' => $trial_period_days ? $trial_period_days : $interval_days);
             if (!trim($plan['statement_descriptor'])) {
                 unset($plan['statement_descriptor']);
             }
             $plan = Stripe_Plan::create($plan);
         }
         self::log_entry(__FUNCTION__, $input_time, $input_vars, time(), $plan);
         return $plan;
         // Stripe plan object.
     } catch (exception $exception) {
         self::log_entry(__FUNCTION__, $input_time, $input_vars, time(), $exception);
         return self::error_message($exception);
     }
 }
 /**
  * Add a new plan to Stripe via API
  *
  * @param $stripe_plan_id string Calculated from level and period
  * @param $int
  * @param $int_count
  * @param $name
  * @param $level_price
  */
 public static function add_plan($stripe_plan_id, $int, $int_count, $name, $level_price)
 {
     global $psts;
     try {
         $currency = self::currency();
         Stripe_Plan::create(array("amount" => round($level_price * 100), "interval" => $int, "interval_count" => $int_count, "name" => "{$name}", "currency" => $currency, "id" => "{$stripe_plan_id}"));
     } catch (Exception $e) {
     }
 }
 private function _checkPlanExists($planName)
 {
     try {
         $p = \Stripe_Plan::retrieve($planName);
         return $p;
     } catch (\Stripe_InvalidRequestError $e) {
         if ($e->getHttpStatus() == '404') {
             return false;
         }
     } catch (\Exception $ex) {
         return false;
     }
     return false;
 }
Beispiel #10
0
 function leaky_paywall_pay_with_stripe($level, $level_id)
 {
     $results = '';
     $settings = get_leaky_paywall_settings();
     $currency = apply_filters('leaky_paywall_stripe_currency', $settings['leaky_paywall_currency']);
     if (in_array(strtoupper($currency), array('BIF', 'DJF', 'JPY', 'KRW', 'PYG', 'VND', 'XAF', 'XPF', 'CLP', 'GNF', 'KMF', 'MGA', 'RWF', 'VUV', 'XOF'))) {
         //Zero-Decimal Currencies
         //https://support.stripe.com/questions/which-zero-decimal-currencies-does-stripe-support
         $stripe_price = number_format($level['price'], '0', '', '');
     } else {
         $stripe_price = number_format($level['price'], '2', '', '');
         //no decimals
     }
     $publishable_key = 'on' === $settings['test_mode'] ? $settings['test_publishable_key'] : $settings['live_publishable_key'];
     if (!empty($level['recurring']) && 'on' === $level['recurring']) {
         try {
             $stripe_plan = false;
             $time = time();
             if (!empty($level['plan_id'])) {
                 //We need to verify that the plan_id matches the level details, otherwise we need to update it
                 try {
                     $stripe_plan = Stripe_Plan::retrieve($level['plan_id']);
                 } catch (Exception $e) {
                     $stripe_plan = false;
                 }
             }
             if (!is_object($stripe_plan) || ($stripe_price != $stripe_plan->amount || $level['interval'] != $stripe_plan->interval || $level['interval_count'] != $stripe_plan->interval_count)) {
                 $args = array('amount' => esc_js($stripe_price), 'interval' => esc_js($level['interval']), 'interval_count' => esc_js($level['interval_count']), 'name' => esc_js($level['label']) . ' ' . $time, 'currency' => esc_js($currency), 'id' => sanitize_title_with_dashes($level['label']) . '-' . $time);
                 $stripe_plan = Stripe_Plan::create($args);
                 $settings['levels'][$level_id]['plan_id'] = $stripe_plan->id;
                 update_leaky_paywall_settings($settings);
             }
             $results .= '<form action="' . esc_url(add_query_arg('issuem-leaky-paywall-stripe-return', '1', get_page_link($settings['page_for_subscription']))) . '" method="post">
                           <input type="hidden" name="custom" value="' . esc_js($level_id) . '" />
                           <script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"
                                   data-key="' . esc_js($publishable_key) . '"
                                   data-plan="' . esc_js($stripe_plan->id) . '" 
                                   data-currency="' . esc_js($currency) . '" 
                                   data-description="' . esc_js($level['label']) . '">
                           </script>
                           ' . apply_filters('leaky_paywall_pay_with_stripe_recurring_payment_form_after_script', '') . '
                         </form>';
         } catch (Exception $e) {
             $results = '<h1>' . sprintf(__('Error processing request: %s', 'issuem-leaky-paywall'), $e->getMessage()) . '</h1>';
         }
     } else {
         $results .= '<form action="' . esc_url(add_query_arg('issuem-leaky-paywall-stripe-return', '1', get_page_link($settings['page_for_subscription']))) . '" method="post">
                       <input type="hidden" name="custom" value="' . esc_js($level_id) . '" />
                       <script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"
                               data-key="' . esc_js($publishable_key) . '"
                               data-amount="' . esc_js($stripe_price) . '" 
                               data-currency="' . esc_js($currency) . '" 
                               data-description="' . esc_js($level['label']) . '">
                       </script>
                           ' . apply_filters('leaky_paywall_pay_with_stripe_non_recurring_payment_form_after_script', '') . '
                     </form>';
     }
     return '<div class="leaky-paywall-stripe-button leaky-paywall-payment-button">' . $results . '</div>';
 }
        public function generate_stripe_form($atts, $content)
        {
            global $WishListMemberInstance;
            $this->load_popup();
            add_action('wp_footer', array($this, 'footer'), 100);
            global $current_user;
            extract(shortcode_atts(array('sku' => null), $atts));
            if (empty($sku)) {
                return null;
            }
            $stripeapikey = $WishListMemberInstance->GetOption('stripeapikey');
            $stripeconnections = $WishListMemberInstance->GetOption('stripeconnections');
            $stripethankyou = $WishListMemberInstance->GetOption('stripethankyou');
            $wpm_scregister = get_site_url() . '/index.php/register/';
            $stripethankyou_url = $wpm_scregister . $stripethankyou;
            $stripesettings = $WishListMemberInstance->GetOption('stripesettings');
            $wpm_levels = $WishListMemberInstance->GetOption('wpm_levels');
            $WishListMemberInstance->InjectPPPSettings($wpm_levels);
            $settings = $stripeconnections[$sku];
            $amt = $settings['amount'];
            $currency = empty($stripesettings['currency']) ? 'USD' : $stripesettings['currency'];
            if ($settings['subscription']) {
                try {
                    Stripe::setApiKey($stripeapikey);
                    $plan = Stripe_Plan::retrieve($settings['plan']);
                    $amt = number_format($plan->amount / 100, 2);
                } catch (Exception $e) {
                    $msg = __("Error %s");
                    return sprintf($msg, $e->getMessage());
                }
            }
            $ppp_level = $WishListMemberInstance->IsPPPLevel($sku);
            $level_name = $wpm_levels[$sku]['name'];
            if ($ppp_level) {
                $level_name = $ppp_level->post_title;
            }
            $heading = empty($stripesettings['formheading']) ? "Register to %level" : $stripesettings['formheading'];
            $heading = str_replace('%level', $level_name, $heading);
            $btn_label = empty($stripesettings['buttonlabel']) ? "Join %level" : $stripesettings['buttonlabel'];
            $btn_label = str_replace('%level', $level_name, $btn_label);
            $panel_btn_label = empty($stripesettings['panelbuttonlabel']) ? "Pay" : $stripesettings['panelbuttonlabel'];
            $panel_btn_label = str_replace('%level', $level_name, $panel_btn_label);
            $logo = $stripesettings['logo'];
            $logo = str_replace('%level', $level_name, $stripesettings['logo']);
            $content = trim($content);
            ob_start();
            ?>

			<?php 
            if (empty($content)) {
                ?>
				<button class="regform-button go-regform" style="width: auto" id="go-regform-<?php 
                echo $sku;
                ?>
" class="" href="#regform-<?php 
                echo $sku;
                ?>
"><?php 
                echo $btn_label;
                ?>
</button>
			<?php 
            } else {
                ?>
				<a id="go-regform-<?php 
                echo $sku;
                ?>
" class="go-regform" href="#regform-<?php 
                echo $sku;
                ?>
"><?php 
                echo $content;
                ?>
</a>
			<?php 
            }
            ?>

			<?php 
            $btn = ob_get_clean();
            ?>

			<?php 
            if (!is_user_logged_in()) {
                $path = sprintf($WishListMemberInstance->pluginDir . '/extlib/wlm_stripe/form_new_fields.php');
                include $path;
                $this->forms[$sku] = wlm_build_payment_form($data);
            } else {
                $stripe_cust_id = $WishListMemberInstance->Get_UserMeta($current_user->ID, 'stripe_cust_id');
                $path = sprintf($WishListMemberInstance->pluginDir . '/extlib/wlm_stripe/form_existing_fields.php');
                include $path;
                $this->forms[$sku] = wlm_build_payment_form($data);
            }
            return $btn;
        }
        if (!function_exists('curl_init')) {
            echo "<div class='error'>" . __('<p><strong>Important! : </strong> Stripe integration requires the CURL PHP extension. Please ask your web hosting provider to enable it.</p>', 'wishlist-member') . "</div>";
        }
        if (!function_exists('json_decode')) {
            echo "<div class='error'>" . __('<p><strong>Important! : </strong> Stripe integration requires the JSON PHP extension. Please ask your web hosting provider to enable it.</p>', 'wishlist-member') . "</div>";
        }
        if (!function_exists('mb_detect_encoding')) {
            echo "<div class='error'>" . __('<p><strong>Important! : </strong> Stripe integration requires the Multibyte String PHP extension. Please ask your web hosting provider to enable it.</p>', 'wishlist-member') . "</div>";
        }
        ?>
		<?php 
        $status = "<span class='wlm-color-warning'>Please provide your Stripe API Keys</span>";
        if (!empty($stripeapikey)) {
            try {
                $status = Stripe::setApiKey($stripeapikey);
                $plans = Stripe_Plan::all(array('count' => MAX_PLAN_COUNT));
                $api_type = strpos($stripeapikey, "test") === false ? "LIVE" : "TEST";
                $status = "<strong><span class='wlm-color-success'>Connected<span></strong> using a <strong>{$api_type}</strong> key.";
            } catch (Exception $e) {
                $status = "<strong><span class='wlm-color-error'>Unable to connect stripe api</span>. Stripe reason:</strong>" . $e->getMessage();
            }
        }
        ?>
		<form method="post" id="stripe_form">
			<h2 class="wlm-integration-steps">Step 1. Setup API Keys</h2>
			<p><?php 
        _e('Get your API Key from ', 'wishlist-member');
        ?>
<a href="https://dashboard.stripe.com/account/apikeys" target="_blank">https://dashboard.stripe.com/account/apikeys</a></p>
			<table class="form-table">
				<tr>
Beispiel #13
0
 public function get_plan($plan_id)
 {
     try {
         $plan = Stripe_Plan::retrieve($plan_id);
     } catch (Stripe_Error $e) {
         /**
          * There is no error type specific to failing to retrieve a subscription when an invalid plan ID is passed. We assume here
          * that any 'invalid_request_error' means that the subscription does not exist even though other errors (like providing
          * incorrect API keys) will also generate the 'invalid_request_error'. There is no way to differentiate these requests
          * without relying on the error message which is more likely to change and not reliable.
          */
         $response = $e->getJsonBody();
         if (rgars($response, 'error/type') != 'invalid_request_error') {
             $plan = $this->authorization_error($e->getMessage());
         } else {
             $plan = false;
         }
     }
     return $plan;
 }
 /**
  * @param Avro\StripeBundle\Model\PlanInterface
  */
 public function create(PlanInterface $plan)
 {
     return \Stripe_Plan::create(array('id' => $plan->getId(), 'name' => $plan->getName(), 'amount' => $plan->getAmountInCents(), 'currency' => $plan->getCurrency(), 'interval' => $plan->getInterval()));
 }
 /**
  * Getting all the plans for the user
  * @param stripe key
  *
  * @return an array with the plans
  */
 public static function getPlans($key)
 {
     $out_plans = array();
     // telling stripe who we are
     Stripe::setApiKey($key);
     // getting the charges
     $returned_object = Stripe_Plan::all();
     // extractin json (this is not the best approach)
     $plans = json_decode(strstr($returned_object, '{'), true);
     // getting relevant fields
     foreach ($plans['data'] as $plan) {
         // updating array
         /*
         interval        - string, one of 'day', 'week', 'month' or 'year'.
                             The frequency with which a subscription should be billed.
         name            - name of the plan
         interval_count  - pos int, with the property 'interval' specifies how frequent is the billing,
                             ex: interval = 'month', interval_count = 3 => billing every 3 month
         amount          - pos int, the price of plan, in cents
         currency        - currency in which the plan is charged (e.g "usd")
         created         - timestamp
         name            - name of plan
         */
         $out_plans[$plan['id']] = array('interval' => $plan['interval'], 'name' => $plan['name'], 'created' => $plan['created'], 'amount' => $plan['amount'], 'currency' => $plan['currency'], 'interval_count' => $plan['interval_count'], 'provider' => 'stripe');
     }
     //foreach
     // returning object
     return $out_plans;
 }
Beispiel #16
0
 function add_plan($stripe_plan_id, $int, $name, $level_price)
 {
     try {
         Stripe_Plan::create(array("amount" => round($level_price * 100), "interval" => $int, "name" => "{$name}", "currency" => "usd", "id" => "{$stripe_plan_id}"));
     } catch (Exception $e) {
         //oh well
     }
 }
Beispiel #17
0
<?php

/**
 * Created by PhpStorm.
 * User: debasis_kar
 * Date: 11/12/2015
 * Time: 1:03 PM
 */
try {
    require_once 'Stripe/lib/Stripe.php';
    Stripe::setApiKey("sk_test_jttNGqAeuCpVoftWPWenb6OO");
    $plan = Stripe_Plan::retrieve("p112");
    $plan->name = "New plan name";
    //$plan->price =2533;
    $planresponse = $plan->save();
    $planresponse = $plan->__toJSON(true);
    print_r($planresponse);
} catch (Stripe_CardError $e) {
}
 public function testCreateCustomerAndSubscribeToPlan()
 {
     $this->StripeComponent->startup($this->Controller);
     Stripe::setApiKey(Configure::read('Stripe.TestSecret'));
     // create a plan for this test
     Stripe_Plan::create(array('amount' => 2000, 'interval' => "month", 'name' => "Test Plan", 'currency' => 'usd', 'id' => 'testplan'));
     Stripe::setApiKey(Configure::read('Stripe.TestSecret'));
     $token = Stripe_Token::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 12, 'exp_year' => 2020, 'cvc' => 777, 'name' => 'Casi Robot', 'address_zip' => '91361')));
     $data = array('stripeToken' => $token->id, 'plan' => 'testplan', 'description' => 'Create Customer & Subscribe to Plan', 'email' => '*****@*****.**');
     $result = $this->StripeComponent->customerCreate($data);
     $this->assertRegExp('/^cus\\_[a-zA-Z0-9]+/', $result['stripe_id']);
     $customer = Stripe_Customer::retrieve($result['stripe_id']);
     $this->assertEquals($result['stripe_id'], $customer->id);
     $this->assertEquals($data['plan'], $customer->subscription->plan->id);
     // delete the plan
     $plan = Stripe_Plan::retrieve('testplan');
     $plan->delete();
     $customer->delete();
 }
Beispiel #19
0
function stripeCreatePlan()
{
    require_once './lib/Stripe.php';
    Stripe::setApiKey("mDZRJuHrjeG3sSKJdmumEZdbGtr1TLDW");
    Stripe_Plan::create(array("amount" => 2000, "interval" => "month", "name" => "Amazing Gold Plan", "currency" => "usd", "id" => "gold"));
}
 /**
  * Submit a recurring payment using Stripe's PHP API:
  * https://stripe.com/docs/api?lang=php
  *
  * @param  array $params assoc array of input parameters for this transaction
  * @param  int $amount transaction amount in USD cents
  * @param  object $stripe_customer Stripe customer object generated by Stripe API
  * 
  * @return array the result in a nice formatted array (or an error object)
  * @public
  */
 function doRecurPayment(&$params, $amount, $stripe_customer)
 {
     switch ($this->_mode) {
         case 'test':
             $transaction_mode = 0;
             break;
         case 'live':
             $transaction_mode = 1;
     }
     $frequency = $params['frequency_unit'];
     $installments = $params['installments'];
     $plan_id = "{$frequency}-{$amount}";
     $stripe_plan_query = CRM_Core_DAO::singleValueQuery("SELECT plan_id FROM civicrm_stripe_plans WHERE plan_id = '{$plan_id}'");
     if (!isset($stripe_plan_query)) {
         $formatted_amount = "\$" . number_format($amount / 100, 2);
         //Create a new Plan
         $stripe_plan = Stripe_Plan::create(array("amount" => $amount, "interval" => $frequency, "name" => "CiviCRM {$frequency}" . 'ly ' . $formatted_amount, "currency" => "usd", "id" => $plan_id));
         CRM_Core_DAO::executeQuery("INSERT INTO civicrm_stripe_plans (plan_id) VALUES ('{$plan_id}')");
     }
     //Attach the Subscription to the Stripe Customer
     $stripe_response = $stripe_customer->updateSubscription(array('prorate' => FALSE, 'plan' => $plan_id));
     $existing_subscription_query = CRM_Core_DAO::singleValueQuery("SELECT invoice_id FROM civicrm_stripe_subscriptions WHERE customer_id = '{$stripe_customer->id}'");
     if (!empty($existing_subscription_query)) {
         //Cancel existing Recurring Contribution in CiviCRM
         $cancel_date = date("Y-m-d H:i:s");
         CRM_Core_DAO::executeQuery("UPDATE civicrm_contribution_recur SET cancel_date = '{$cancel_date}', contribution_status_id = '3' WHERE invoice_id = '{$existing_subscription_query}'");
         //Delete the Stripe Subscription from our cron watch list.
         CRM_Core_DAO::executeQuery("DELETE FROM civicrm_stripe_subscriptions WHERE invoice_id = '{$existing_subscription_query}'");
     }
     //Calculate timestamp for the last installment
     $end_time = strtotime("+{$installments} {$frequency}");
     $invoice_id = $params['invoiceID'];
     CRM_Core_DAO::executeQuery("INSERT INTO civicrm_stripe_subscriptions (customer_id, invoice_id, end_time, is_live) VALUES ('{$stripe_customer->id}', '{$invoice_id}', '{$end_time}', '{$transaction_mode}')");
     $params['trxn_id'] = $stripe_response->id;
     return $params;
 }
 /**
  * @param int $count number to return, max 100
  * @param int $offset where to start
  * @return array|bool array with data property that contains array of all plans up to count.
  */
 function get_all($count = 10, $offset = 0)
 {
     try {
         $plans = Stripe_Plan::all();
     } catch (Exception $e) {
         $this->error = TRUE;
         $this->message = $e->getMessage();
         $this->code = $e->getCode();
         return FALSE;
     }
     return $plans;
 }
     if (!empty($customer_name)) {
         $plan_desc .= " - {$customer_name}";
     }
     $plan_id = "form{$form_id}_entry{$payment_record_id}";
     //if paid trial enabled, create an invoice item
     if (!empty($payment_enable_trial) && !empty($payment_trial_amount)) {
         $trial_charge_amount = $payment_trial_amount * 100;
         //charge in cents
         $trial_charge_desc = "Trial Period Payment for (Form #{$form_id} - Entry #{$payment_record_id})";
         if (!empty($customer_name)) {
             $trial_charge_desc .= " - {$customer_name}";
         }
         Stripe_InvoiceItem::create(array("customer" => $customer_obj, "amount" => $trial_charge_amount, "currency" => $payment_currency, "description" => $trial_charge_desc));
     }
     //create subscription plan
     Stripe_Plan::create(array("amount" => $charge_amount, "interval" => $payment_recurring_unit, "interval_count" => $payment_recurring_cycle, "trial_period_days" => $trial_period_days, "name" => $plan_desc, "currency" => $payment_currency, "id" => $plan_id));
     //subscribe the customer to the plan
     $subscribe_result = $customer_obj->updateSubscription(array("plan" => $plan_id));
     if (!empty($subscribe_result->status)) {
         $payment_success = true;
     }
 } else {
     //this is non recurring payment
     $charge_desc = "Payment for (Form #{$form_id} - Entry #{$payment_record_id})";
     if (!empty($customer_name)) {
         $charge_desc .= " - {$customer_name}";
     }
     //charge the customer
     $charge_result = Stripe_Charge::create(array("amount" => $charge_amount, "currency" => $payment_currency, "customer" => $customer_obj->id, "description" => $charge_desc));
     if ($charge_result->paid === true) {
         $payment_success = true;
Beispiel #23
0
 public function get_all_plans()
 {
     $plans = Stripe_Plan::all();
     return $plans->data;
 }
		function subscribe(&$order)
		{
			//create a code for the order
			if(empty($order->code))
				$order->code = $order->getRandomCode();
			
			//setup customer
			$this->getCustomer($order);
			if(empty($this->customer))
				return false;	//error retrieving customer
			
			//figure out the amounts
			$amount = $order->PaymentAmount;
			$amount_tax = $order->getTaxForPrice($amount);
			$order->subtotal = $amount;
			$amount = round((float)$amount + (float)$amount_tax, 2);

			/*
				There are two parts to the trial. Part 1 is simply the delay until the first payment
				since we are doing the first payment as a separate transaction.
				The second part is the actual "trial" set by the admin.
				
				Stripe only supports Year or Month for billing periods, but we account for Days and Weeks just in case.
			*/
			//figure out the trial length (first payment handled by initial charge)			
			if($order->BillingPeriod == "Year")
				$trial_period_days = $order->BillingFrequency * 365;	//annual
			elseif($order->BillingPeriod == "Day")
				$trial_period_days = $order->BillingFrequency * 1;		//daily
			elseif($order->BillingPeriod == "Week")
				$trial_period_days = $order->BillingFrequency * 7;		//weekly
			else
				$trial_period_days = $order->BillingFrequency * 30;	//assume monthly
				
			//convert to a profile start date
			$order->ProfileStartDate = date("Y-m-d", strtotime("+ " . $trial_period_days . " Day")) . "T0:0:0";			
			
			//filter the start date
			$order->ProfileStartDate = apply_filters("pmpro_profile_start_date", $order->ProfileStartDate, $order);			

			//convert back to days
			$trial_period_days = ceil(abs(strtotime(date("Y-m-d")) - strtotime($order->ProfileStartDate)) / 86400);

			//now add the actual trial set by the site
			if(!empty($order->TrialBillingCycles))						
			{
				$trialOccurrences = (int)$order->TrialBillingCycles;
				if($order->BillingPeriod == "Year")
					$trial_period_days = $trial_period_days + (365 * $order->BillingFrequency * $trialOccurrences);	//annual
				elseif($order->BillingPeriod == "Day")
					$trial_period_days = $trial_period_days + (1 * $order->BillingFrequency * $trialOccurrences);		//daily
				elseif($order->BillingPeriod == "Week")
					$trial_period_days = $trial_period_days + (7 * $order->BillingFrequency * $trialOccurrences);	//weekly
				else
					$trial_period_days = $trial_period_days + (30 * $order->BillingFrequency * $trialOccurrences);	//assume monthly				
			}					
			
			//create a plan
			try
			{						
				$plan = Stripe_Plan::create(array(
				  "amount" => $amount * 100,
				  "interval_count" => $order->BillingFrequency,
				  "interval" => strtolower($order->BillingPeriod),
				  "trial_period_days" => $trial_period_days,
				  "name" => $order->membership_name . " for order " . $order->code,
				  "currency" => strtolower(pmpro_getOption("currency")),
				  "id" => $order->code)
				);
			}
			catch (Exception $e)
			{
				$order->error = "Error creating plan with Stripe:" . $e->getMessage();
				$order->shorterror = $order->error;
				return false;
			}
			
			//subscribe to the plan
			try
			{				
				$this->customer->updateSubscription(array("prorate" => false, "plan" => $order->code));
			}
			catch (Exception $e)
			{
				//try to delete the plan
				$plan->delete();
				
				//return error
				$order->error = "Error subscribing customer to plan with Stripe:" . $e->getMessage();
				$order->shorterror = $order->error;
				return false;
			}
			
			//delete the plan
			$plan = Stripe_Plan::retrieve($plan['id']);
			$plan->delete();		

			//if we got this far, we're all good						
			$order->status = "success";		
			$order->subscription_transaction_id = $this->customer['id'];	//transaction id is the customer id, we save it in user meta later too			
			return true;
		}	
Beispiel #25
0
 $token = $_POST['stripeToken'];
 $multiple = $_POST['multiple'];
 $amount_total_cents = $amount_total * 100;
 $amount_subscribe_cents = $amount_subscribe * 100;
 $amount_diff_cents = $amount_diff * 100;
 $message = "Amount Total: " . $amount_total . "<br/>";
 $message .= "Amount Subscribe: " . $amount_subscribe . "<br/>";
 $message .= "Amount Difference (OTP): " . $amount_diff . "<br/>";
 $message .= "Amount Difference (OTP) in Cents: " . $amount_diff_cents . "<br/>";
 $ng_plan_name = $_POST['planname'];
 $ng_plan_id = $_POST['planid'];
 $description_otp = "Invoice #" . $smartyvalues["invoiceid"] . " - " . $email . " - One Time Services";
 $stripe_plan_name = "Invoice #" . $smartyvalues['invoiceid'] . ' - ' . $ng_plan_name . ' - ' . $email;
 // Create "custom" plan for this user
 try {
     Stripe_Plan::create(array("amount" => $amount_subscribe_cents, "interval" => "month", "name" => $stripe_plan_name, "currency" => "usd", "id" => $ng_plan_id));
     // Find out if this customer already has a paying item with stripe and if they have a subscription with it
     $current_uid = $_SESSION['uid'];
     $q = mysql_query("SELECT subscriptionid FROM tblhosting WHERE userid='" . $current_uid . "' AND paymentmethod='stripe' AND subscriptionid !=''");
     if (mysql_num_rows($q) > 0) {
         $data = mysql_fetch_array($q);
         $stripe_customer_id = $data[0];
     } else {
         $stripe_customer_id = "";
     }
     if ($stripe_customer_id == "") {
         $customer = Stripe_Customer::create(array("card" => $token, "plan" => $ng_plan_id, "email" => $email));
         $cust_id = $customer->id;
         $q = mysql_query("UPDATE tblhosting SET subscriptionid='" . $cust_id . "' WHERE id='" . $ng_plan_id . "'");
     } else {
         // Create the customer from scratch
Beispiel #26
0
 function getPlan()
 {
     global $stripeConfig;
     $resp['code'] = '';
     $resp['message'] = '';
     try {
         $resp = Stripe_Plan::retrieve($stripeConfig["plan"]);
         return $resp;
     } catch (Stripe_CardError $e) {
         $body = $e->getJsonBody();
         $resp = $body['error'];
         return $resp;
     } catch (Stripe_InvalidRequestError $e) {
         // Invalid parameters were supplied to Stripe's API
         $body = $e->getJsonBody();
         $resp = $body['error'];
         return $resp;
     } catch (Stripe_AuthenticationError $e) {
         // Authentication with Stripe's API failed
         // (maybe you changed API keys recently)
         $body = $e->getJsonBody();
         $resp = $body['error'];
         return $resp;
     } catch (Stripe_ApiConnectionError $e) {
         // Network communication with Stripe failed
         $body = $e->getJsonBody();
         $resp = $body['error'];
         return $resp;
     } catch (Stripe_Error $e) {
         // Display a very generic error to the user, and maybe send
         // yourself an email
         $body = $e->getJsonBody();
         $resp = $body['error'];
         return $resp;
     } catch (Exception $e) {
         // Something else happened, completely unrelated to Stripe
         $body = $e->getJsonBody();
         $resp = $body['error'];
         return $resp;
     }
     // if nothing is returned above, return null.  should never happen.
     return null;
 }
 /**
  * Sync plans with Stripe
  */
 public function syncAction()
 {
     \Stripe::setApiKey($this->container->getParameter('avro_stripe.secret_key'));
     $planManager = $this->container->get('avro_stripe.plan.manager');
     $plans = $planManager->findAll();
     foreach ($plans as $plan) {
         $planManager->remove($plan);
     }
     $plans = \Stripe_Plan::all()->data;
     foreach ($plans as $plan) {
         $p = $planManager->create();
         $p->setId($plan->id);
         $p->setName($plan->name);
         $p->setInterval($plan->interval);
         $p->setAmount($plan->amount);
         $p->setCurrency($plan->currency);
         $planManager->update($p);
     }
     $this->container->get('session')->setFlash('success', 'plan.synced.flash');
     return new RedirectResponse($this->container->get('router')->generate('avro_stripe_plan_list'));
 }
Beispiel #28
-1
 /**
  * Verify that a plan with a given ID exists, or create a new one if it does
  * not.
  */
 protected static function retrieveOrCreatePlan($id)
 {
     authorizeFromEnv();
     try {
         $plan = Stripe_Plan::retrieve($id);
     } catch (Stripe_InvalidRequestError $exception) {
         $plan = Stripe_Plan::create(array('id' => $id, 'amount' => 0, 'currency' => 'usd', 'interval' => 'month', 'name' => 'Gold Test Plan'));
     }
 }
Beispiel #29
-1
 /**
  * Process STRIPE payment
  * @global type $invoice
  */
 static function process_payment()
 {
     global $invoice;
     //** Response */
     $response = array('success' => false, 'error' => false, 'data' => null);
     if (isset($_POST['stripeToken'])) {
         $token = $_POST['stripeToken'];
     } else {
         $response['error'] = true;
         $data['messages'][] = __('The order cannot be processed. You have not been charged. Please confirm that you have JavaScript enabled and try again.', WPI);
         $response['data'] = $data;
         die(json_encode($response));
     }
     try {
         if (!class_exists('Stripe')) {
             require_once WPI_Path . '/third-party/stripe/lib/Stripe.php';
         }
         $pk = trim($invoice['billing']['wpi_stripe']['settings'][$invoice['billing']['wpi_stripe']['settings']['mode']['value'] . '_secret_key']['value']);
         Stripe::setApiKey($pk);
         switch ($invoice['type'] == 'recurring') {
             //** If recurring */
             case true:
                 $plan = Stripe_Plan::create(array("amount" => (double) $invoice['net'] * 100, "interval" => $invoice['recurring']['wpi_stripe']['interval'], "interval_count" => $invoice['recurring']['wpi_stripe']['interval_count'], "name" => $invoice['post_title'], "currency" => strtolower($invoice['default_currency_code']), "id" => $invoice['invoice_id']));
                 $customer = Stripe_Customer::create(array("card" => $token, "plan" => $invoice['invoice_id'], "email" => $invoice['user_email']));
                 if (!empty($plan->id) && !empty($plan->amount) && !empty($customer->id)) {
                     $invoice_obj = new WPI_Invoice();
                     $invoice_obj->load_invoice("id={$invoice['invoice_id']}");
                     $log = sprintf(__("Subscription has been initiated. Plan: %s, Customer: %s", WPI), $plan->id, $customer->id);
                     $invoice_obj->add_entry("attribute=invoice&note={$log}&type=update");
                     $invoice_obj->save_invoice();
                     update_post_meta(wpi_invoice_id_to_post_id($invoice['invoice_id']), '_stripe_customer_id', $customer->id);
                     $data['messages'][] = __('Stripe Subscription has been initiated. Do not pay this invoice again. Thank you.', WPI);
                     $response['success'] = true;
                     $response['error'] = false;
                 } else {
                     $data['messages'][] = __('Could not initiate Stripe Subscription. Contact site Administrator please.', WPI);
                     $response['success'] = false;
                     $response['error'] = true;
                 }
                 break;
                 //** If regular payment */
             //** If regular payment */
             case false:
                 //** Support partial payments */
                 if ($invoice['deposit_amount'] > 0) {
                     $amount = (double) $_REQUEST['amount'];
                     if ((double) $_REQUEST['amount'] > $invoice['net']) {
                         $amount = $invoice['net'];
                     }
                     if ((double) $_REQUEST['amount'] < $invoice['deposit_amount']) {
                         $amount = $invoice['deposit_amount'];
                     }
                 } else {
                     $amount = $invoice['net'];
                 }
                 $charge = Stripe_Charge::create(array("amount" => (double) $amount * 100, "currency" => strtolower($invoice['default_currency_code']), "card" => $token, "description" => $invoice['invoice_id'] . ' [' . $invoice['post_title'] . ' / ' . get_bloginfo('url') . ' / ' . $invoice['user_email'] . ']'));
                 if ($charge->paid) {
                     $invoice_id = $invoice['invoice_id'];
                     $wp_users_id = $invoice['user_data']['ID'];
                     //** update user data */
                     update_user_meta($wp_users_id, 'last_name', !empty($_REQUEST['last_name']) ? $_REQUEST['last_name'] : '');
                     update_user_meta($wp_users_id, 'first_name', !empty($_REQUEST['first_name']) ? $_REQUEST['first_name'] : '');
                     update_user_meta($wp_users_id, 'city', !empty($_REQUEST['city']) ? $_REQUEST['city'] : '');
                     update_user_meta($wp_users_id, 'state', !empty($_REQUEST['state']) ? $_REQUEST['state'] : '');
                     update_user_meta($wp_users_id, 'zip', !empty($_REQUEST['zip']) ? $_REQUEST['zip'] : '');
                     update_user_meta($wp_users_id, 'streetaddress', !empty($_REQUEST['address1']) ? $_REQUEST['address1'] : '');
                     update_user_meta($wp_users_id, 'phonenumber', !empty($_REQUEST['phonenumber']) ? $_REQUEST['phonenumber'] : '');
                     update_user_meta($wp_users_id, 'country', !empty($_REQUEST['country']) ? $_REQUEST['country'] : '');
                     if (!empty($_REQUEST['crm_data'])) {
                         self::user_meta_updated($_REQUEST['crm_data']);
                     }
                     $invoice_obj = new WPI_Invoice();
                     $invoice_obj->load_invoice("id={$invoice['invoice_id']}");
                     $amount = (double) ($charge->amount / 100);
                     //** Add payment amount */
                     $event_note = WPI_Functions::currency_format($amount, $invoice['invoice_id']) . __(" paid via STRIPE", WPI);
                     $event_amount = $amount;
                     $event_type = 'add_payment';
                     $event_note = urlencode($event_note);
                     //** Log balance changes */
                     $invoice_obj->add_entry("attribute=balance&note={$event_note}&amount={$event_amount}&type={$event_type}");
                     //** Log client IP */
                     $success = __("Successfully processed by ", WPI) . $_SERVER['REMOTE_ADDR'];
                     $invoice_obj->add_entry("attribute=invoice&note={$success}&type=update");
                     //** Log payer */
                     $payer_card = __("STRIPE Card ID: ", WPI) . $charge->card->id;
                     $invoice_obj->add_entry("attribute=invoice&note={$payer_card}&type=update");
                     $invoice_obj->save_invoice();
                     //** Mark invoice as paid */
                     wp_invoice_mark_as_paid($invoice_id, $check = true);
                     send_notification($invoice);
                     $data['messages'][] = __('Successfully paid. Thank you.', WPI);
                     $response['success'] = true;
                     $response['error'] = false;
                 } else {
                     $data['messages'][] = $charge->failure_message;
                     $response['success'] = false;
                     $response['error'] = true;
                 }
                 break;
                 //** Other cases */
             //** Other cases */
             default:
                 break;
         }
         $response['data'] = $data;
         die(json_encode($response));
     } catch (Stripe_CardError $e) {
         $e_json = $e->getJsonBody();
         $err = $e_json['error'];
         $response['error'] = true;
         $data['messages'][] = $err['message'];
     } catch (Stripe_ApiConnectionError $e) {
         $response['error'] = true;
         $data['messages'][] = __('Service is currently unavailable. Please try again later.', WPI);
     } catch (Stripe_InvalidRequestError $e) {
         $response['error'] = true;
         $data['messages'][] = __('Unknown error occured. Please contact site administrator.', WPI);
     } catch (Stripe_ApiError $e) {
         $response['error'] = true;
         $data['messages'][] = __('Stripe server is down! Try again later.', WPI);
     } catch (Exception $e) {
         $response['error'] = true;
         $data['messages'][] = $e->getMessage();
     }
     $response['data'] = $data;
     die(json_encode($response));
 }
 /**
  * Create a new subscription with Stripe
  *
  * @since 1.4
  */
 function subscribe(&$order, $checkout = true)
 {
     global $pmpro_currency;
     //create a code for the order
     if (empty($order->code)) {
         $order->code = $order->getRandomCode();
     }
     //filter order before subscription. use with care.
     $order = apply_filters("pmpro_subscribe_order", $order, $this);
     //figure out the user
     if (!empty($order->user_id)) {
         $user_id = $order->user_id;
     } else {
         global $current_user;
         $user_id = $current_user->ID;
     }
     //set up customer
     $result = $this->getCustomer($order);
     if (empty($result)) {
         return false;
     }
     //error retrieving customer
     //set subscription id to custom id
     $order->subscription_transaction_id = $this->customer['id'];
     //transaction id is the customer id, we save it in user meta later too
     //figure out the amounts
     $amount = $order->PaymentAmount;
     $amount_tax = $order->getTaxForPrice($amount);
     $amount = round((double) $amount + (double) $amount_tax, 2);
     /*
     	There are two parts to the trial. Part 1 is simply the delay until the first payment
     	since we are doing the first payment as a separate transaction.
     	The second part is the actual "trial" set by the admin.
     
     	Stripe only supports Year or Month for billing periods, but we account for Days and Weeks just in case.
     */
     //figure out the trial length (first payment handled by initial charge)
     if ($order->BillingPeriod == "Year") {
         $trial_period_days = $order->BillingFrequency * 365;
     } elseif ($order->BillingPeriod == "Day") {
         $trial_period_days = $order->BillingFrequency * 1;
     } elseif ($order->BillingPeriod == "Week") {
         $trial_period_days = $order->BillingFrequency * 7;
     } else {
         $trial_period_days = $order->BillingFrequency * 30;
     }
     //assume monthly
     //convert to a profile start date
     $order->ProfileStartDate = date("Y-m-d", strtotime("+ " . $trial_period_days . " Day", current_time("timestamp"))) . "T0:0:0";
     //filter the start date
     $order->ProfileStartDate = apply_filters("pmpro_profile_start_date", $order->ProfileStartDate, $order);
     //convert back to days
     $trial_period_days = ceil(abs(strtotime(date("Y-m-d"), current_time("timestamp")) - strtotime($order->ProfileStartDate, current_time("timestamp"))) / 86400);
     //for free trials, just push the start date of the subscription back
     if (!empty($order->TrialBillingCycles) && $order->TrialAmount == 0) {
         $trialOccurrences = (int) $order->TrialBillingCycles;
         if ($order->BillingPeriod == "Year") {
             $trial_period_days = $trial_period_days + 365 * $order->BillingFrequency * $trialOccurrences;
         } elseif ($order->BillingPeriod == "Day") {
             $trial_period_days = $trial_period_days + 1 * $order->BillingFrequency * $trialOccurrences;
         } elseif ($order->BillingPeriod == "Week") {
             $trial_period_days = $trial_period_days + 7 * $order->BillingFrequency * $trialOccurrences;
         } else {
             $trial_period_days = $trial_period_days + 30 * $order->BillingFrequency * $trialOccurrences;
         }
         //assume monthly
     } elseif (!empty($order->TrialBillingCycles)) {
         /*
         	Let's set the subscription to the trial and give the user an "update" to change the sub later to full price (since v2.0)
         
         	This will force TrialBillingCycles > 1 to act as if they were 1
         */
         $new_user_updates = array();
         $new_user_updates[] = array('when' => 'payment', 'billing_amount' => $order->PaymentAmount, 'cycle_period' => $order->BillingPeriod, 'cycle_number' => $order->BillingFrequency);
         //now amount to equal the trial #s
         $amount = $order->TrialAmount;
         $amount_tax = $order->getTaxForPrice($amount);
         $amount = round((double) $amount + (double) $amount_tax, 2);
     }
     //create a plan
     try {
         $plan = array("amount" => $amount * 100, "interval_count" => $order->BillingFrequency, "interval" => strtolower($order->BillingPeriod), "trial_period_days" => $trial_period_days, "name" => $order->membership_name . " for order " . $order->code, "currency" => strtolower($pmpro_currency), "id" => $order->code);
         $plan = Stripe_Plan::create(apply_filters('pmpro_stripe_create_plan_array', $plan));
     } catch (Exception $e) {
         $order->error = __("Error creating plan with Stripe:", "pmpro") . $e->getMessage();
         $order->shorterror = $order->error;
         return false;
     }
     //before subscribing, let's clear out the updates so we don't trigger any during sub
     if (!empty($user_id)) {
         $old_user_updates = get_user_meta($user_id, "pmpro_stripe_updates", true);
         update_user_meta($user_id, "pmpro_stripe_updates", array());
     }
     if (empty($order->subscription_transaction_id) && !empty($this->customer['id'])) {
         $order->subscription_transaction_id = $this->customer['id'];
     }
     //subscribe to the plan
     try {
         $subscription = array("plan" => $order->code);
         $result = $this->customer->subscriptions->create(apply_filters('pmpro_stripe_create_subscription_array', $subscription));
     } catch (Exception $e) {
         //try to delete the plan
         $plan->delete();
         //give the user any old updates back
         if (!empty($user_id)) {
             update_user_meta($user_id, "pmpro_stripe_updates", $old_user_updates);
         }
         //return error
         $order->error = __("Error subscribing customer to plan with Stripe:", "pmpro") . $e->getMessage();
         $order->shorterror = $order->error;
         return false;
     }
     //delete the plan
     $plan = Stripe_Plan::retrieve($order->code);
     $plan->delete();
     //if we got this far, we're all good
     $order->status = "success";
     $order->subscription_transaction_id = $result['id'];
     //save new updates if this is at checkout
     if ($checkout) {
         //empty out updates unless set above
         if (empty($new_user_updates)) {
             $new_user_updates = array();
         }
         //update user meta
         if (!empty($user_id)) {
             update_user_meta($user_id, "pmpro_stripe_updates", $new_user_updates);
         } else {
             //need to remember the user updates to save later
             global $pmpro_stripe_updates;
             $pmpro_stripe_updates = $new_user_updates;
             function pmpro_user_register_stripe_updates($user_id)
             {
                 global $pmpro_stripe_updates;
                 update_user_meta($user_id, "pmpro_stripe_updates", $pmpro_stripe_updates);
             }
             add_action("user_register", "pmpro_user_register_stripe_updates");
         }
     } else {
         //give them their old updates back
         update_user_meta($user_id, "pmpro_stripe_updates", $old_user_updates);
     }
     return true;
 }