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 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);
 }
 /**
  * @param $plan_id           unique ID for this plan
  * @param $plan_name         Name to display in web interface and on invoices
  * @param $amount            amount in PENNIES.  0 for free plan
  * @param $interval          'month' or 'year'
  * @param bool $trial_period if integer, number of days for trial period
  */
 function insert($plan_id, $plan_name, $amount, $interval, $trial_period = FALSE)
 {
     $plan_data = array('amount' => $amount, 'interval' => $interval, 'name' => $plan_name, 'currency' => 'usd', 'id' => $plan_id);
     if ($trial_period) {
         $plan_data['trial_period_days'] = $trial_period;
     }
     try {
         $plan = Stripe_Plan::create($plan_data);
     } catch (Exception $e) {
         $this->error = TRUE;
         $this->message = $e->getMessage();
         $this->code = $e->getCode();
         return FALSE;
     }
     return $plan;
 }
Beispiel #5
0
 /**
  * @method POST
  */
 function post()
 {
     // get an authuser
     $authUser = new AuthUser();
     if (isset($authUser->UserUniqId)) {
         // check if authorized
         if ($authUser->IsSuperAdmin == true) {
             // only available to super admin
             try {
                 parse_str($this->request->data, $request);
                 // parse request
                 $id = $request['id'];
                 $name = $request['name'];
                 $amount = $request['amount'];
                 $interval = $request['interval'];
                 $currency = $request['currency'];
                 $trial = $request['trial'];
                 $plan = array("amount" => $amount, "interval" => $interval, "name" => $name, "currency" => $currency, "trial_period_days" => $trial, "id" => $id);
                 // add plan to stripe
                 Stripe::setApiKey(STRIPE_API_KEY);
                 Stripe_Plan::create($plan);
                 // return a json response
                 $response = new Tonic\Response(Tonic\Response::OK);
                 $response->contentType = 'application/json';
                 $response->body = json_encode($plan);
                 return $response;
             } catch (Exception $e) {
                 $response = new Tonic\Response(Tonic\Response::BADREQUEST);
                 $response->body = $e->getMessage();
                 return $response;
             }
         }
     } else {
         // unauthorized access
         return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
     }
 }
Beispiel #6
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
     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;
 /**
  * Create the recurring payment profile.
  */
 private function create_recurring_payment_plan(SI_Checkouts $checkout, SI_Invoice $invoice)
 {
     self::setup_stripe();
     try {
         $invoice_id = $invoice->get_id();
         $term = SI_Subscription_Payments::get_term($invoice_id);
         // day, week, month, or year
         $duration = (int) SI_Subscription_Payments::get_duration($invoice_id);
         $price = SI_Subscription_Payments::get_renew_price($invoice_id);
         // Recurring Plan the customer will be changed to.
         $plan = Stripe_Plan::create(array('amount' => self::convert_money_to_cents(sprintf('%0.2f', $price)), 'currency' => self::get_currency_code($invoice_id), 'interval' => $term, 'name' => get_the_title($invoice_id), 'id' => $invoice_id . self::convert_money_to_cents(sprintf('%0.2f', $price))));
         do_action('si_log', __CLASS__ . '::' . __FUNCTION__ . ' - Stripe PLAN Response', $plan);
         do_action('si_stripe_recurring_payment_plan_created', $plan);
         // Return something for the response
         return true;
     } catch (Exception $e) {
         self::set_error_messages($e->getMessage());
         return false;
     }
 }
Beispiel #9
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 #10
0
 /**
  * Subscribe the user to a Stripe plan. This process works like so:
  *
  * 1 - Get existing plan or create new plan (plan ID generated by feed name, id and recurring amount).
  * 2 - Create new customer.
  * 3 - Create new subscription by subscribing custerom to plan.
  *
  * @param  [type] $auth            [description]
  * @param  [type] $feed            [description]
  * @param  [type] $submission_data [description]
  * @param  [type] $form            [description]
  * @param  [type] $entry           [description]
  *
  * @return [type]                  [description]
  */
 public function subscribe($feed, $submission_data, $form, $entry)
 {
     $this->populate_credit_card_last_four($form);
     $this->include_stripe_api();
     if ($this->get_stripe_js_error()) {
         return $this->authorization_error($this->get_stripe_js_error());
     }
     $payment_amount = $submission_data['payment_amount'];
     $single_payment_amount = $submission_data['setup_fee'];
     $trial_period_days = rgars($feed, 'meta/trialPeriod') ? rgars($feed, 'meta/trialPeriod') : null;
     $plan_id = $this->get_subscription_plan_id($feed, $payment_amount);
     $plan = $this->get_plan($plan_id);
     if (rgar($plan, 'error_message')) {
         return $plan;
     }
     try {
         if (!$plan) {
             $plan = Stripe_Plan::create(array('interval' => $feed['meta']['billingCycle_unit'], 'interval_count' => $feed['meta']['billingCycle_length'], 'name' => $feed['meta']['feedName'], 'currency' => GFCommon::get_currency(), 'id' => $plan_id, 'amount' => $payment_amount * 100, 'trial_period_days' => $trial_period_days));
         }
         $stripe_response = $this->get_stripe_js_response();
         $email = $this->get_mapped_field_value('customerInformation_email', $form, $entry, $feed['meta']);
         $description = $this->get_mapped_field_value('customerInformation_description', $form, $entry, $feed['meta']);
         $customer = Stripe_Customer::create(array('description' => $description, 'email' => $email, 'card' => $stripe_response->id, 'account_balance' => $single_payment_amount * 100));
         $subscription = $customer->updateSubscription(array('plan' => $plan->id));
     } catch (Stripe_Error $e) {
         return $this->authorization_error($e->getMessage());
     }
     return array('is_success' => true, 'subscription_id' => $subscription->id, 'customer_id' => $customer->id, 'amount' => $payment_amount);
 }
 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 #12
0
 /**
  * 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) {
     }
 }
Beispiel #13
0
 public function stripe_createPlan($params)
 {
     /*
     * Stripe_Plan::create(array(
     		  "amount" => 2000,
     		  "interval" => "month",
     		  "name" => "Amazing Gold Plan",
     		  "currency" => "usd",
     		  "id" => "gold"));
     */
     try {
         Stripe_Plan::create(['amount' => $params['amount'] * 100, 'interval' => $params['interval'], 'name' => $params['name'], 'interval_count' => $params['count'], 'currency' => 'usd', 'id' => $params['id'], 'trial_period_days' => $params['trial']]);
         return true;
     } catch (Exception $e) {
         $this->log("Unable to Create Plan:  " . $e->getMessage(), 'stripe');
         return $e->getMessage();
     }
 }
 /**
  * Subscribe the user to a Stripe plan. This process works like so:
  *
  * 1 - Get existing plan or create new plan (plan ID generated by feed name, id and recurring amount).
  * 2 - Create new customer.
  * 3 - Create new subscription by subscribing customer to plan.
  *
  * @param array $feed The feed object currently being processed.
  * @param array $submission_data The customer and transaction data.
  * @param array $form The form object currently being processed.
  * @param array $entry The entry object currently being processed.
  *
  * @return array
  */
 public function subscribe($feed, $submission_data, $form, $entry)
 {
     $this->include_stripe_api();
     if ($this->get_stripe_js_error()) {
         return $this->authorization_error($this->get_stripe_js_error());
     }
     $payment_amount = $submission_data['payment_amount'];
     $single_payment_amount = $submission_data['setup_fee'];
     $trial_period_days = rgars($feed, 'meta/trialPeriod') ? $submission_data['trial'] : null;
     $currency = rgar($entry, 'currency');
     $plan_id = $this->get_subscription_plan_id($feed, $payment_amount, $trial_period_days);
     $plan = $this->get_plan($plan_id);
     if (rgar($plan, 'error_message')) {
         return $plan;
     }
     try {
         if (!$plan) {
             $plan_meta = array('interval' => $feed['meta']['billingCycle_unit'], 'interval_count' => $feed['meta']['billingCycle_length'], 'name' => $feed['meta']['feedName'], 'currency' => $currency, 'id' => $plan_id, 'amount' => $this->get_amount_export($payment_amount, $currency), 'trial_period_days' => $trial_period_days);
             $this->log_debug(__METHOD__ . '(): Plan to be created => ' . print_r($plan_meta, 1));
             $plan = Stripe_Plan::create($plan_meta);
         }
         $stripe_response = $this->get_stripe_js_response();
         $customer_meta = array('description' => $this->get_field_value($form, $entry, rgar($feed['meta'], 'customerInformation_description')), 'email' => $this->get_field_value($form, $entry, rgar($feed['meta'], 'customerInformation_email')), 'card' => $stripe_response->id, 'account_balance' => $this->get_amount_export($single_payment_amount, $currency), 'metadata' => $this->get_stripe_meta_data($feed, $entry, $form));
         $coupon_field_id = rgar($feed['meta'], 'customerInformation_coupon');
         $coupon = $this->maybe_override_field_value(rgar($entry, $coupon_field_id), $form, $entry, $coupon_field_id);
         if ($coupon) {
             $customer_meta['coupon'] = $coupon;
         }
         $this->log_debug(__METHOD__ . '(): Customer meta to be created => ' . print_r($customer_meta, 1));
         $customer = Stripe_Customer::create($customer_meta);
         if (has_filter('gform_stripe_customer_after_create')) {
             $this->log_debug(__METHOD__ . '(): Executing functions hooked to gform_stripe_customer_after_create.');
         }
         /**
          * Allow custom actions to be performed between the customer being created and subscribed to the plan.
          *
          * @param Stripe_Customer $customer The Stripe customer object.
          * @param array $feed The feed currently being processed.
          * @param array $entry The entry currently being processed.
          * @param array $form The form currently being processed.
          *
          */
         do_action('gform_stripe_customer_after_create', $customer, $feed, $entry, $form);
         $subscription = $customer->updateSubscription(array('plan' => $plan->id));
     } catch (Stripe_Error $e) {
         return $this->authorization_error($e->getMessage());
     }
     return array('is_success' => true, 'subscription_id' => $subscription->id, 'customer_id' => $customer->id, 'amount' => $payment_amount);
 }
Beispiel #15
0
 /**
  * Create a new Stripe plan
  * @param array $data
  * @return Stripe_Plan|false
  */
 public function createPlan($data = array())
 {
     $fields = array('id', 'amount', 'currency', 'interval', 'interval_count', 'name', 'trial_period_days', 'metadata', 'statement_description');
     try {
         foreach ($data as $key => $value) {
             if (!in_array($key, $fields)) {
                 $data[$key] = '';
             }
         }
         $data = array_filter($data);
         return Stripe_Plan::create($data, $this->access_token);
     } catch (Exception $ex) {
         $this->log($ex);
         return false;
     }
 }
Beispiel #16
0
    public static function start_payment($invoice_id, $payment_amount, $invoice_payment_id, $user_id = false)
    {
        if ($invoice_id && $payment_amount && $invoice_payment_id) {
            // we are starting a payment via stripe!
            // setup a pending payment and redirect to stripe.
            $invoice_data = module_invoice::get_invoice($invoice_id);
            if (!$user_id) {
                $user_id = $invoice_data['user_id'];
            }
            if (!$user_id) {
                $user_id = isset($invoice_data['primary_user_id']) ? $invoice_data['primary_user_id'] : 0;
            }
            if (!$user_id) {
                $user_id = module_security::get_loggedin_id();
            }
            $user_data = module_user::get_user($user_id);
            if (!$user_data || !strpos($user_data['email'], '@')) {
                die('Please ensure your user account has a valid email address before paying with stripe');
            }
            $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id);
            // we add the fee details to the invoice payment record so that the new invoice total can be calculated.
            $fee_percent = module_config::c('payment_method_stripe_charge_percent', 0);
            $fee_amount = module_config::c('payment_method_stripe_charge_amount', 0);
            $fee_description = module_config::c('payment_method_stripe_charge_description', 'Stripe Fee');
            $fee_total = 0;
            if ($fee_percent != 0 || $fee_amount != 0) {
                $fee_total = module_invoice::calculate_fee($invoice_id, $invoice_data, $payment_amount, array('percent' => $fee_percent, 'amount' => $fee_amount, 'description' => $fee_description));
                if ($fee_total != 0) {
                    // add this percent/amount to the invoice payment
                    $payment_amount = $payment_amount + $fee_total;
                    update_insert('invoice_payment_id', $invoice_payment_id, 'invoice_payment', array('fee_percent' => $fee_percent, 'fee_amount' => $fee_amount, 'fee_description' => $fee_description, 'fee_total' => $fee_total, 'amount' => $payment_amount));
                }
            }
            // we check if this payment is a recurring payment or a standard one off payment.
            if (module_config::c('payment_method_stripe_subscriptions', 0)) {
                // we support subscriptions!
                // first check if the subscription module is active, and if this invoice is part of an active subscription.
                $is_subscription = false;
                if (class_exists('module_subscription', false)) {
                    $subscription_history = get_single('subscription_history', 'invoice_id', $invoice_id);
                    if ($subscription_history && $subscription_history['subscription_id']) {
                        // this invoice is for a subscription! woo!
                        // work out when we should bill for this subscription.
                        $subscription = module_subscription::get_subscription($subscription_history['subscription_id']);
                        $subscription_owner = module_subscription::get_subscription_owner($subscription_history['subscription_owner_id']);
                        if ($subscription_owner['owner_table'] && $subscription_owner['owner_id']) {
                            // work out when the next invoice will be generated for this subscription.
                            $members_subscriptions = module_subscription::get_subscriptions_by($subscription_owner['owner_table'], $subscription_owner['owner_id']);
                            if (isset($members_subscriptions[$subscription_history['subscription_id']])) {
                                $member_subscription = $members_subscriptions[$subscription_history['subscription_id']];
                                // everything checks out! good to go....
                                // for now we just do a basic "EVERY X TIME" subscription
                                // todo: work out how long until next generate date, and set that (possibly smaller) time period as the first portion of the subscription
                                /*echo '<pre>';
                                  print_r($subscription_history);
                                  print_r($subscription);
                                  print_r($subscription_owner);
                                  print_r($member_subscription);
                                  exit;*/
                                $is_subscription = array();
                                if ($subscription['days'] > 0) {
                                    $is_subscription['days'] = $subscription['days'];
                                }
                                if ($subscription['months'] > 0) {
                                    $is_subscription['months'] = $subscription['months'];
                                }
                                if ($subscription['years'] > 0) {
                                    $is_subscription['years'] = $subscription['years'];
                                }
                                if (count($is_subscription)) {
                                    $is_subscription['name'] = $subscription['name'];
                                    $is_subscription['id'] = $subscription_history['subscription_id'];
                                }
                            }
                        }
                    }
                }
                // todo: check if this invoice has a manual renewal date, perform subscription feature as above.
                if ($is_subscription) {
                    $bits = array();
                    if (isset($is_subscription['days']) && $is_subscription['days'] > 0) {
                        $bits[] = _l('%s days', $is_subscription['days']);
                    }
                    if (isset($is_subscription['months']) && $is_subscription['months'] > 0) {
                        $bits[] = _l('%s months', $is_subscription['months']);
                    }
                    if (isset($is_subscription['years']) && $is_subscription['years'] > 0) {
                        $bits[] = _l('%s years', $is_subscription['years']);
                    }
                    $invoice_payment_data = module_invoice::get_invoice_payment($invoice_payment_id);
                    if (isset($invoice_payment_data['invoice_payment_subscription_id']) && (int) $invoice_payment_data['invoice_payment_subscription_id'] > 0) {
                        // existing subscription already!
                        // not really sure what to do here, just redirect to stripe as if the user is doing it for the first time.
                        $_REQUEST['payment_subscription'] = true;
                        // hacks!
                    }
                    if (isset($_REQUEST['payment_subscription']) || module_config::c('payment_method_stripe_force_subscription', 0)) {
                        // user is setting up a subscription! yes!!
                        // we create an entry in our database for this particular subscription
                        // or if one exists for this payment already then we just continue with that (ie: the user is going in again to redo it)
                        // setup a new subscription in the database for us.
                        if (isset($invoice_payment_data['invoice_payment_subscription_id']) && (int) $invoice_payment_data['invoice_payment_subscription_id'] > 0) {
                            $invoice_payment_subscription_id = $invoice_payment_data['invoice_payment_subscription_id'];
                        } else {
                            $invoice_payment_subscription_id = update_insert('invoice_payment_subscription_id', false, 'invoice_payment_subscription', array('status' => _INVOICE_SUBSCRIPTION_PENDING, 'days' => isset($is_subscription['days']) ? $is_subscription['days'] : 0, 'months' => isset($is_subscription['months']) ? $is_subscription['months'] : 0, 'years' => isset($is_subscription['years']) ? $is_subscription['years'] : 0, 'date_start' => '0000-00-00', 'date_last_pay' => '0000-00-00', 'date_next' => '0000-00-00'));
                            update_insert('invoice_payment_id', $invoice_payment_id, 'invoice_payment', array('invoice_payment_subscription_id' => $invoice_payment_subscription_id));
                        }
                        $description = _l('Recurring payment for %s every %s', $is_subscription['name'], implode(', ', $bits));
                        $subscription_name = $is_subscription['name'];
                        unset($is_subscription['name']);
                        // so reset/key cals below rosk.
                        $subscription_id = $is_subscription['id'];
                        unset($is_subscription['id']);
                        // so reset/key cals below rosk.
                        $currency = module_config::get_currency($invoice_payment_data['currency_id']);
                        // if there are more than 1 recurring amounts then we convert it to weeks, as stripe only supports one time period.
                        if (count($is_subscription) > 1) {
                            $days = isset($is_subscription['days']) ? $is_subscription['days'] : 0;
                            if (isset($is_subscription['months'])) {
                                $days += $is_subscription['months'] * 30;
                                unset($is_subscription['months']);
                            }
                            if (isset($is_subscription['years'])) {
                                $days += $is_subscription['years'] * 365;
                                unset($is_subscription['years']);
                            }
                            $is_subscription['days'] = $days;
                        }
                        reset($is_subscription);
                        $time = key($is_subscription);
                        if ($time == 'days') {
                            // convert days to weeks
                            //$time = 'week';
                            $time = 'day';
                            $period = $is_subscription['days'];
                            //$period = max(1,floor($is_subscription['days'] / 7));
                        } else {
                            if ($time == 'months') {
                                $time = 'month';
                                $period = $is_subscription['months'];
                            } else {
                                if ($time == 'years') {
                                    $time = 'year';
                                    $period = $is_subscription['years'];
                                } else {
                                    die('Failed to create subscription, invalid settings');
                                }
                            }
                        }
                        $stripe_amount = $payment_amount * 100;
                        ini_set('display_errors', true);
                        ini_set('error_reporting', E_ALL);
                        // create or retrieve this subscription.
                        require_once 'includes/plugin_paymethod_stripe/stripe-php/lib/Stripe.php';
                        $stripe = array("secret_key" => module_config::c('payment_method_stripe_secret_key'), "publishable_key" => module_config::c('payment_method_stripe_publishable_key'));
                        Stripe::setApiKey($stripe['secret_key']);
                        $stripe_plan_id = 'sub_' . $subscription_id;
                        $stripe_plan = false;
                        if ($stripe_plan_id) {
                            // get this plan from stripe, and check it's still valid:
                            try {
                                $stripe_plan = Stripe_Plan::retrieve($stripe_plan_id);
                            } catch (Exception $e) {
                                //print_r($e);
                            }
                            if ($stripe_plan && $stripe_plan->interval == $time && $stripe_plan->interval_count == $period && $stripe_plan->amount == $stripe_amount) {
                                // still have a valid plan! yes!
                            } else {
                                // plan no longer exists or has changed
                                $stripe_plan = false;
                            }
                        }
                        if (!$stripe_plan) {
                            try {
                                $settings = array("amount" => $stripe_amount, "interval" => $time, 'interval_count' => $period, "name" => $subscription_name, "currency" => $currency['code'], "id" => $stripe_plan_id, 'metadata' => array('subscription_id' => $subscription_id));
                                $stripe_plan = Stripe_Plan::create($settings);
                            } catch (Exception $e) {
                                //print_r($e);
                            }
                            //                            print_r($stripe_plan);
                        }
                        if ($stripe_plan) {
                            // right to go!
                            // display the stripe payment form (same as stripe_form.php, just we do a subscription rather than once off payment)
                            //self::stripe_redirect($description,$payment_amount,$user_id,$invoice_payment_id,$invoice_id,$invoice_payment_data['currency_id']);
                            $currency = module_config::get_currency($invoice_payment_data['currency_id']);
                            $currency_code = $currency['code'];
                            $template = new module_template();
                            ob_start();
                            ?>
                                <h1><?php 
                            echo htmlspecialchars($description);
                            ?>
</h1>
                                <form action="<?php 
                            echo full_link(_EXTERNAL_TUNNEL . '?m=paymethod_stripe&h=pay_subscription&method=stripe');
                            ?>
" method="post">
                                    <input type="hidden" name="invoice_payment_subscription_id" value="<?php 
                            echo $invoice_payment_subscription_id;
                            ?>
">
                                    <input type="hidden" name="invoice_payment_id" value="<?php 
                            echo $invoice_payment_id;
                            ?>
">
                                    <input type="hidden" name="invoice_id" value="<?php 
                            echo $invoice_id;
                            ?>
">
                                    <input type="hidden" name="stripe_plan_id" value="<?php 
                            echo $stripe_plan_id;
                            ?>
">
                                    <input type="hidden" name="description" value="<?php 
                            echo htmlspecialchars($description);
                            ?>
">
                                    <input type="hidden" name="user_id" value="<?php 
                            echo htmlspecialchars($user_id);
                            ?>
">
                                  <script src="https://checkout.stripe.com/v2/checkout.js" class="stripe-button"
                                          data-key="<?php 
                            echo $stripe['publishable_key'];
                            ?>
"
                                          data-amount="<?php 
                            echo $payment_amount * 100;
                            ?>
"
                                          <?php 
                            if (isset($user_data['email']) && strlen($user_data['email'])) {
                                ?>
                                          data-email="<?php 
                                echo htmlspecialchars($user_data['email']);
                                ?>
"
                                            <?php 
                            }
                            ?>
                                          data-currency="<?php 
                            echo htmlspecialchars($currency_code);
                            ?>
"
                                          data-label="<?php 
                            _e('Pay %s by Credit Card', dollar($payment_amount, true, $invoice_payment_data['currency_id']));
                            ?>
"
                                          data-description="<?php 
                            echo htmlspecialchars($description);
                            ?>
"></script>
                                </form>

                                <p>&nbsp;</p>
                                <p>

                                <a href="<?php 
                            echo module_invoice::link_public($invoice_id);
                            ?>
"><?php 
                            _e("Cancel");
                            ?>
</a>
                                </p>
                                <?php 
                            $template->content = ob_get_clean();
                            echo $template->render('pretty_html');
                            exit;
                        } else {
                            die('Failed to create stripe plan. Please check settings: ' . var_export($stripe_plan, true));
                        }
                    } else {
                        if (isset($_REQUEST['payment_single'])) {
                            // use is choosing to continue payment as a once off amount
                        } else {
                            // give the user an option
                            module_template::init_template('invoice_payment_subscription', '<h2>Payment for Invoice {INVOICE_NUMBER}</h2>
                        <p>Please choose from the available payment options below:</p>
                        <form action="{PAYMENT_URL}" method="post">
                        <input type="hidden" name="invoice_payment_id" value="{INVOICE_PAYMENT_ID}">
                        <input type="hidden" name="payment_method" value="{PAYMENT_METHOD}">
                        <input type="hidden" name="payment_amount" value="{PAYMENT_AMOUNT}">
                        <p><input type="submit" name="payment_single" value="Pay a Once Off amount of {PRETTY_PAYMENT_AMOUNT}"></p>
                        <p><input type="submit" name="payment_subscription" value="Setup Automatic Payments of {PRETTY_PAYMENT_AMOUNT} every {SUBSCRIPTION_PERIOD}"></p>
                        </form>
                        ', 'Used when a customer tries to pay an invoice that has a subscription option.', 'code');
                            $template = module_template::get_template_by_key('invoice_payment_subscription');
                            $template->page_title = htmlspecialchars($invoice_data['name']);
                            $template->assign_values($invoice_payment_data);
                            $template->assign_values(module_invoice::get_replace_fields($invoice_data['invoice_id'], $invoice_data));
                            $template->assign_values(array('invoice_payment_id' => $invoice_payment_id, 'payment_url' => module_invoice::link_public_pay($invoice_data['invoice_id']), 'payment_method' => 'paymethod_stripe', 'payment_amount' => $payment_amount, 'pretty_payment_amount' => dollar($payment_amount, true, $invoice_data['currency_id']), 'subscription_period' => implode(', ', $bits), 'fee_amount' => dollar($fee_amount, true, $invoice_data['currency_id']), 'fee_total' => dollar($fee_total, true, $invoice_data['currency_id']), 'fee_percent' => $fee_percent, 'fee_description' => $fee_description));
                            echo $template->render('pretty_html');
                            exit;
                        }
                    }
                }
            }
            $description = _l('Payment for invoice %s', $invoice_data['name']);
            //self::stripe_redirect($description,$payment_amount,$user_id,$invoice_payment_id,$invoice_id,$invoice_payment_data['currency_id']);
            $currency = module_config::get_currency($invoice_payment_data['currency_id']);
            $currency_code = $currency['code'];
            $template = new module_template();
            ob_start();
            include module_theme::include_ucm('includes/plugin_paymethod_stripe/pages/stripe_form.php');
            $template->content = ob_get_clean();
            echo $template->render('pretty_html');
            exit;
        }
        return false;
    }
 /**
  * Run Stripe calls through this to catch exceptions gracefully.
  * @param  string $op
  *   Determine which operation to perform.
  * @param  array $params
  *   Parameters to run Stripe calls on.
  * @return varies
  *   Response from gateway.
  */
 function stripeCatchErrors($op = 'create_customer', &$params, $qfKey = '')
 {
     // @TODO:  Handle all calls through this using $op switching for sanity.
     // Check for errors before trying to submit.
     try {
         switch ($op) {
             case 'create_customer':
                 $return = Stripe_Customer::create($params);
                 break;
             case 'charge':
                 $return = Stripe_Charge::create($params);
                 break;
             case 'save':
                 $return = $params->save();
                 break;
             case 'create_plan':
                 $return = Stripe_Plan::create($params);
                 break;
             default:
                 $return = Stripe_Customer::create($params);
                 break;
         }
     } catch (Stripe_CardError $e) {
         $error_message = '';
         // Since it's a decline, Stripe_CardError will be caught
         $body = $e->getJsonBody();
         $err = $body['error'];
         //$error_message .= 'Status is: ' . $e->getHttpStatus() . "<br />";
         ////$error_message .= 'Param is: ' . $err['param'] . "<br />";
         $error_message .= 'Type: ' . $err['type'] . "<br />";
         $error_message .= 'Code: ' . $err['code'] . "<br />";
         $error_message .= 'Message: ' . $err['message'] . "<br />";
         // Check Event vs Contribution for redirect.  There must be a better way.
         if (empty($params['selectMembership']) && empty($params['contributionPageID'])) {
             $error_url = CRM_Utils_System::url('civicrm/event/register', "_qf_Main_display=1&cancel=1&qfKey={$qfKey}", FALSE, NULL, FALSE);
         } else {
             $error_url = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=1&cancel=1&qfKey={$qfKey}", FALSE, NULL, FALSE);
         }
         CRM_Core_Error::statusBounce("Oops!  Looks like there was an error.  Payment Response:\n        <br /> {$error_message}", $error_url);
     } catch (Stripe_InvalidRequestError $e) {
         // Invalid parameters were supplied to Stripe's API
     } catch (Stripe_AuthenticationError $e) {
         // Authentication with Stripe's API failed
         // (maybe you changed API keys recently)
     } catch (Stripe_ApiConnectionError $e) {
         // Network communication with Stripe failed
     } catch (Stripe_Error $e) {
         // Display a very generic error to the user, and maybe send
         // yourself an email
     } catch (Exception $e) {
         // Something else happened, completely unrelated to Stripe
         $error_message = '';
         // Since it's a decline, Stripe_CardError will be caught
         $body = $e->getJsonBody();
         $err = $body['error'];
         //$error_message .= 'Status is: ' . $e->getHttpStatus() . "<br />";
         ////$error_message .= 'Param is: ' . $err['param'] . "<br />";
         $error_message .= 'Type: ' . $err['type'] . "<br />";
         $error_message .= 'Code: ' . $err['code'] . "<br />";
         $error_message .= 'Message: ' . $err['message'] . "<br />";
         if (empty($params['selectMembership']) && empty($params['contributionPageID'])) {
             $error_url = CRM_Utils_System::url('civicrm/event/register', "_qf_Main_display=1&cancel=1&qfKey={$qfKey}", FALSE, NULL, FALSE);
         } else {
             $error_url = CRM_Utils_System::url('civicrm/contribute/transact', "_qf_Main_display=1&cancel=1&qfKey={$qfKey}", FALSE, NULL, FALSE);
         }
         CRM_Core_Error::statusBounce("Oops!  Looks like there was an error.  Payment Response:\n        <br /> {$error_message}", $error_url);
     }
     return $return;
 }
 public function createPlan($customer, $payment, $interval)
 {
     $amount = $this->getTotalAmount($payment);
     $currency = $payment->currency_code;
     $description = $amount / 100 . ' ' . $currency . ' / ' . $interval;
     $existing_id = db_select('stripe_payment_plans', 'p')->fields('p', array('id'))->condition('payment_interval', $interval)->condition('amount', $amount)->condition('currency', $currency)->execute()->fetchField();
     if ($existing_id) {
         return $existing_id;
     } else {
         $params = array('id' => $description, 'amount' => $amount, 'payment_interval' => $interval, 'name' => 'donates ' . $description, 'currency' => $currency);
         \Drupal::database()->insert('stripe_payment_plans')->fields($params)->execute();
         // This ugly hack is necessary because 'interval' is a reserved keyword
         // in mysql and drupal does not enclose the field names in '"'.
         $params['interval'] = $params['payment_interval'];
         unset($params['payment_interval']);
         unset($params['pid']);
         return \Stripe_Plan::create($params)->id;
     }
 }
 private function _createPlan($planName, ChargeModel &$model)
 {
     $response = array();
     $planId = $planName;
     try {
         $p = \Stripe_Plan::create(array("amount" => $model->planAmount, "interval" => $model->planInterval, "interval_count" => $model->planIntervalCount, "name" => $planName, "currency" => $model->planCurrency, "id" => $planId, "trial_period_days" => null));
         return $p;
     } catch (\Exception $e) {
         $this->errors[] = $e->getMessage();
         return false;
     }
     return false;
 }
Beispiel #20
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>';
 }
 /**
  * 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);
     }
 }
Beispiel #22
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;
 }
Beispiel #24
0
 /**
  * Subscribe the user to a Stripe plan. This process works like so:
  *
  * 1 - Get existing plan or create new plan (plan ID generated by feed name, id and recurring amount).
  * 2 - Create new customer.
  * 3 - Create new subscription by subscribing customer to plan.
  *
  * @param array $feed The feed object currently being processed.
  * @param array $submission_data The customer and transaction data.
  * @param array $form The form object currently being processed.
  * @param array $entry The entry object currently being processed.
  *
  * @return array
  */
 public function subscribe($feed, $submission_data, $form, $entry)
 {
     $this->populate_credit_card_last_four($form);
     $this->include_stripe_api();
     if ($this->get_stripe_js_error()) {
         return $this->authorization_error($this->get_stripe_js_error());
     }
     $payment_amount = $submission_data['payment_amount'];
     $single_payment_amount = $submission_data['setup_fee'];
     $trial_period_days = rgars($feed, 'meta/trialPeriod') ? rgars($feed, 'meta/trialPeriod') : null;
     $currency = rgar($entry, 'currency');
     $plan_id = $this->get_subscription_plan_id($feed, $payment_amount);
     $plan = $this->get_plan($plan_id);
     if (rgar($plan, 'error_message')) {
         return $plan;
     }
     try {
         if (!$plan) {
             $plan_meta = array('interval' => $feed['meta']['billingCycle_unit'], 'interval_count' => $feed['meta']['billingCycle_length'], 'name' => $feed['meta']['feedName'], 'currency' => $currency, 'id' => $plan_id, 'amount' => $this->get_amount_export($payment_amount, $currency), 'trial_period_days' => $trial_period_days);
             $this->log_debug(__METHOD__ . '(): Plan to be created => ' . print_r($plan_meta, 1));
             $plan = Stripe_Plan::create($plan_meta);
         }
         $stripe_response = $this->get_stripe_js_response();
         $customer_meta = array('description' => $this->get_field_value($form, $entry, rgar($feed['meta'], 'customerInformation_description')), 'email' => $this->get_field_value($form, $entry, rgar($feed['meta'], 'customerInformation_email')), 'card' => $stripe_response->id, 'account_balance' => $this->get_amount_export($single_payment_amount, $currency), 'metadata' => $this->get_stripe_meta_data($feed, $entry, $form));
         $coupon_field_id = rgar($feed['meta'], 'customerInformation_coupon');
         $coupon = $this->maybe_override_field_value(rgar($entry, $coupon_field_id), $form, $entry, $coupon_field_id);
         if ($coupon) {
             $customer_meta['coupon'] = $coupon;
         }
         $this->log_debug(__METHOD__ . '(): Customer meta to be created => ' . print_r($customer_meta, 1));
         $customer = Stripe_Customer::create($customer_meta);
         $subscription = $customer->updateSubscription(array('plan' => $plan->id));
     } catch (Stripe_Error $e) {
         return $this->authorization_error($e->getMessage());
     }
     return array('is_success' => true, 'subscription_id' => $subscription->id, 'customer_id' => $customer->id, 'amount' => $payment_amount);
 }
		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 #26
0
/**
 * Gets the stripe plan associated with the level, and creates one if it doesn't exist
 *
 * @since 4.0.0
 */
function leaky_paywall_get_stripe_plan($level, $level_id, $plan_args)
{
    $settings = get_leaky_paywall_settings();
    $stripe_plan = false;
    $time = time();
    Stripe::setApiKey($plan_args['secret_key']);
    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) || ($plan_args['stripe_price'] != $stripe_plan->amount || $level['interval'] != $stripe_plan->interval || $level['interval_count'] != $stripe_plan->interval_count)) {
        $args = array('amount' => esc_js($plan_args['stripe_price']), 'interval' => esc_js($level['interval']), 'interval_count' => esc_js($level['interval_count']), 'name' => esc_js($level['label']) . ' ' . $time, 'currency' => esc_js($plan_args['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);
    }
    return $stripe_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()));
 }
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'));
     }
 }
 /**
  * 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;
 }
Beispiel #30
-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));
 }