コード例 #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;
 }
コード例 #2
0
ファイル: stripe_api.php プロジェクト: jrdncchr/merlinleads
 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');
 }
コード例 #3
0
ファイル: plan.php プロジェクト: eavesmonkey/respond
 /**
  * @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'];
                 // add plan to stripe
                 Stripe::setApiKey(STRIPE_API_KEY);
                 $p = Stripe_Plan::retrieve($id);
                 $p->name = $name;
                 $p->save();
                 // return a json response
                 $response = new Tonic\Response(Tonic\Response::OK);
                 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);
     }
 }
コード例 #4
0
 /**
  * @param $id Plan id
  */
 public function retrieve($id)
 {
     try {
         return \Stripe_Plan::retrieve($id);
     } catch (\Exception $e) {
         return false;
     }
 }
コード例 #5
0
ファイル: PlanTest.php プロジェクト: JSpier/smacamp
 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);
 }
コード例 #6
0
 /**
  * Gets a plan object.
  *
  * @param $plan_id the unique plan id
  * @return mixed plan, or FALSE
  */
 function get($plan_id)
 {
     try {
         $plan = Stripe_Plan::retrieve($plan_id);
     } catch (Exception $e) {
         $this->error = TRUE;
         $this->message = $e->getMessage();
         $this->code = $e->getCode();
         return FALSE;
     }
     return $plan;
 }
コード例 #7
0
ファイル: Subscription.php プロジェクト: dioscouri/f3-striper
 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');
     }
 }
コード例 #8
0
ファイル: class-gf-stripe.php プロジェクト: TMBR/johnjohn
 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;
 }
コード例 #9
0
 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();
 }
コード例 #10
0
 /**
  * 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);
     }
 }
コード例 #11
0
 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;
 }
コード例 #12
0
        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;
        }
コード例 #13
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;
    }
コード例 #14
0
ファイル: StripeClient.php プロジェクト: Daltonmedia/stripe
 /**
  * Get a subscription plan
  * @param string $plan_id
  * @return Stripe_Plan|false
  */
 public function getPlan($plan_id = '')
 {
     try {
         return Stripe_Plan::retrieve($plan_id, $this->access_token);
     } catch (Exception $ex) {
         $this->log($ex);
         return false;
     }
 }
コード例 #15
0
ファイル: stripe.trt.php プロジェクト: carriercomm/atikit
 public function stripe_getPlan($id)
 {
     $plan = Stripe_Plan::retrieve($id);
     return $plan;
 }
コード例 #16
0
ファイル: gateway-stripe.php プロジェクト: hscale/webento
 function delete_plan($stripe_plan_id)
 {
     try {
         $plan = Stripe_Plan::retrieve($stripe_plan_id);
         $plan->delete();
     } catch (Exception $e) {
         //oh well
     }
 }
コード例 #17
0
ファイル: plan_update.php プロジェクト: samsujj/pbs_landing
<?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) {
}
コード例 #18
0
ファイル: deprecated.php プロジェクト: zeen101/leaky-paywall
 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>';
 }
コード例 #19
0
		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;
		}	
コード例 #20
0
ファイル: functions.php プロジェクト: zeen101/leaky-paywall
/**
 * 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;
}
コード例 #21
0
ファイル: StripeConfig.php プロジェクト: 76tech/codesamples
 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;
 }
コード例 #22
-1
ファイル: TestCase.php プロジェクト: JSpier/smacamp
 /**
  * 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'));
     }
 }
コード例 #23
-1
 /**
  * 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;
 }