/** * @param array $process_data * @param $blog_id * @param $domain * * @return bool */ public static function process_checkout_form($process_data = array(), $blog_id, $domain) { global $psts, $current_user, $current_site; $site_name = $current_site->site_name; $img_base = $psts->plugin_url . 'images/'; $session_keys = array('new_blog_details', 'upgraded_blog_details', 'COUPON_CODE', 'activation_key'); foreach ($session_keys as $key) { $process_data[$key] = isset($process_data[$key]) ? $process_data[$key] : ProSites_Helper_Session::session($key); } if (!empty($domain)) { $site_name = !empty($_POST['blogname']) ? $_POST['blogname'] : !empty($_POST['signup_email']) ? $_POST['signup_email'] : ''; } //Process Checkout if (isset($_POST['cc_stripe_checkout']) && 1 == (int) $_POST['cc_stripe_checkout']) { //check for level, if empty don't go ahead and return if (empty($_POST['level']) || empty($_POST['period'])) { $psts->errors->add('general', __('Please choose your desired level and payment plan.', 'psts')); return false; } else { if (!isset($_POST['stripeToken']) && empty($_POST['wp_password'])) { $psts->errors->add('general', __('There was an error processing your Credit Card with Stripe. Please try again.', 'psts')); } } // TAX Object $tax_object = ProSites_Helper_Session::session('tax_object'); if (empty($tax_object) || empty($tax_object->evidence)) { $tax_object = ProSites_Helper_Tax::get_tax_object(); ProSites_Helper_Session::session('tax_object', $tax_object); } $evidence_string = ProSites_Helper_Tax::get_evidence_string($tax_object); $error = ''; $success = ''; $plan = self::get_plan_id($_POST['level'], $_POST['period']); $customer_id = ''; $current_plan_level = 0; $activation_key = isset($_POST['activation']) ? $_POST['activation'] : ''; $email = !empty($_POST['user_email']) ? $_POST['user_email'] : (!empty($_POST['signup_email']) ? $_POST['signup_email'] : (!empty($_POST['blog_email']) ? $_POST['blog_email'] : '')); $blog_id = !empty($blog_id) ? $blog_id : isset($_REQUEST['bid']) ? (int) $_REQUEST['bid'] : 0; //If there is a blog id, fetch existing customer details (Upgrade) if (!empty($blog_id)) { $customer_id = self::get_customer_data($blog_id)->customer_id; $email = isset($current_user->user_email) ? $current_user->user_email : get_blog_option($blog_id, 'admin_email'); //Get current plan for the user if ($current_plan = self::get_current_plan($blog_id)) { list($current_plan_level, $current_plan_period) = explode('_', $current_plan); } } else { //New Signup if (empty($email) && isset($process_data['new_blog_details']) && isset($process_data['new_blog_details']['user_email'])) { $email = $process_data['new_blog_details']['user_email']; } $customer_id = self::get_customer_data(false, false, $email)->customer_id; } if (!self::plan_exists($plan)) { $psts->errors->add('general', sprintf(__('Stripe plan %1$s does not exist.', 'psts'), $plan)); return; } //Create s Stripe profile for the customer with all the available details, //If customer already exists, retrieve customer from stripe try { if (!$customer_id) { try { $customer_args = array('email' => $email, 'description' => sprintf(__('%s user', 'psts'), $site_name), 'card' => $_POST['stripeToken'], 'metadata' => array('domain' => $domain)); $user = get_user_by('email', $email); if ($user) { $blog_string = ''; $customer_args['metadata']['user'] = $user->user_login; $customer_args['description'] = sprintf(__('%s user - %s ', 'psts'), $site_name, $user->first_name . ' ' . $user->last_name); $user_blogs = get_blogs_of_user($user->ID); foreach ($user_blogs as $user_blog) { $blog_string .= $user_blog->blogname . ', '; } $customer_args['metadata']['blogs'] = $blog_string; } if (!$domain) { unset($customer_args['metadata']['domain']); } $c = Stripe_Customer::create($customer_args); } catch (Exception $e) { $psts->errors->add('general', __('The Stripe customer could not be created. Please try again.', 'psts')); return; } //Update the stripe customer id, this is temporary, will be overridden by subscription or charge id self::set_customer_data($blog_id, $c->id, 'ak_' . $activation_key); $customer_id = $c->id; $new = true; } else { // Get a customer if they exist try { $c = Stripe_Customer::retrieve($customer_id); } catch (Exception $e) { $psts->errors->add('general', __('The Stripe customer could not be retrieved. Please try again.', 'psts')); return; } $c->description = sprintf(__('%s user', 'psts'), $site_name); $c->email = $email; $user = get_user_by('email', $email); if ($user) { $blog_string = ''; $c->metadata->user = $user->user_login; $c->description = sprintf(__('%s user - %s ', 'psts'), $site_name, $user->first_name . ' ' . $user->last_name); $user_blogs = get_blogs_of_user($user->ID); foreach ($user_blogs as $user_blog) { $blog_string .= $user_blog->blogname . ', '; } $c->metadata->blogs = $blog_string; } $c->save(); $new = false; //validate wp password (if applicable) if (!empty($_POST['wp_password']) && !wp_check_password($_POST['wp_password'], $current_user->data->user_pass, $current_user->ID)) { $psts->errors->add('general', __('The password you entered is incorrect.', 'psts')); return; } } //prepare vars $currency = self::currency(); $amount_off = false; $paymentAmount = $initAmount = $psts->get_level_setting($_POST['level'], 'price_' . $_POST['period']); $trial_days = $psts->get_setting('trial_days', 0); $cp_code = false; $setup_fee = (double) $psts->get_setting('setup_fee', 0); $has_coupon = isset($process_data['COUPON_CODE']) && ProSites_Helper_Coupons::check_coupon($process_data['COUPON_CODE'], $blog_id, $_POST['level'], $_POST['period'], $domain) ? true : false; $has_setup_fee = $psts->has_setup_fee($blog_id, $_POST['level']); $recurring = $psts->get_setting('recurring_subscriptions', 1); if ($has_setup_fee) { $initAmount = $setup_fee + $paymentAmount; } if ($has_coupon || $has_setup_fee) { $lifetime = 'once'; if ($has_coupon) { //apply coupon $adjusted_values = ProSites_Helper_Coupons::get_adjusted_level_amounts($process_data['COUPON_CODE']); $coupon_obj = ProSites_Helper_Coupons::get_coupon($process_data['COUPON_CODE']); $lifetime = isset($coupon_obj['lifetime']) && 'indefinite' == $coupon_obj['lifetime'] ? 'forever' : 'once'; // $coupon_value = $psts->coupon_value( $process_data['COUPON_CODE'], $paymentAmount ); $coupon_value = $adjusted_values[$_POST['level']]['price_' . $_POST['period']]; // $amount_off = $paymentAmount - $coupon_value['new_total']; $amount_off = $paymentAmount - $coupon_value; $initAmount -= $amount_off; $initAmount = 0 > $initAmount ? 0 : $initAmount; // avoid negative $cpn = false; //Create a stripe coupon if it doesn't exists already try { $cpn = Stripe_Coupon::create(array('amount_off' => $amount_off * 100, 'duration' => $lifetime, 'currency' => $currency, 'max_redemptions' => 1)); } catch (Exception $e) { $psts->errors->add('general', __('Temporary Stripe coupon could not be generated correctly. Please try again.', 'psts')); return; } $cp_code = $cpn->id; } //Check if it's a recurring subscription if ($recurring) { $recurringAmmount = 'forever' == $lifetime && $has_coupon ? $coupon_value : $paymentAmount; if ($_POST['period'] == 1) { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first month, then %2$s each month', 'psts'), $psts->format_currency($currency, $initAmount), $psts->format_currency($currency, $recurringAmmount)); } else { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for the first %2$s month period, then %3$s every %4$s months', 'psts'), $psts->format_currency($currency, $initAmount), $_POST['period'], $psts->format_currency($currency, $recurringAmmount), $_POST['period']); } } else { if (!empty($blog_id)) { $initAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $initAmount); } if ($_POST['period'] == 1) { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $initAmount)); } else { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $initAmount), $_POST['period']); } } } elseif ($recurring) { if ($_POST['period'] == 1) { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s each month', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency); } else { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s %2$s every %3$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $currency, $_POST['period']); } } else { //New Signups if (!empty($blog_id)) { $paymentAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $paymentAmount); } if ($_POST['period'] == 1) { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for 1 month', 'psts'), $psts->format_currency($currency, $paymentAmount)); } else { $desc = $site_name . ' ' . $psts->get_level_setting($_POST['level'], 'name') . ': ' . sprintf(__('%1$s for %2$s months', 'psts'), $psts->format_currency($currency, $paymentAmount), $_POST['period']); } } // Override the Stripe description $desc = apply_filters('psts_stripe_checkout_desc', $desc, $_POST['period'], $_POST['level'], $paymentAmount, $initAmount, $blog_id, $domain); // Time to process invoices with Stripe if ($recurring) { // Recurring subscription // Assign plan to customer $args = array("plan" => $plan, "prorate" => true); // Apply tax? if ($tax_object->apply_tax) { $args['tax_percent'] = $tax_object->tax_rate * 100; } // If there is a coupon, add its reference if ($cp_code) { $args["coupon"] = $cp_code; } // If this is a trial before the subscription starts if ($psts->is_trial_allowed($blog_id)) { if (isset($process_data['new_blog_details']) || !$psts->is_existing($blog_id)) { //customer is new - add trial days $args['trial_end'] = strtotime('+ ' . $trial_days . ' days'); } elseif (is_pro_trial($blog_id) && $psts->get_expire($blog_id) > time()) { //customer's trial is still valid - carry over existing expiration date $args['trial_end'] = $psts->get_expire($blog_id); } } // Meta data for `pay before blog` creation $args['metadata'] = array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level']); if ($tax_object->apply_tax) { $args['metadata']['tax_evidence'] = $evidence_string; } if (!$domain) { unset($args['metadata']['domain']); } // new blog if (isset($_POST['activation'])) { $args['metadata']['activation'] = $_POST['activation']; } // Create Stripe Invoice for the setup fee if ($has_setup_fee) { try { $customer_args = array('customer' => $customer_id, 'amount' => $setup_fee * 100, 'currency' => $currency, 'description' => __('One-time setup fee', 'psts'), 'metadata' => array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level'], 'setup_fee' => 'yes')); if ($tax_object->apply_tax) { $customer_args['metadata']['tax_evidence'] = $evidence_string; } if (!$domain) { unset($customer_args['metadata']['domain']); } // new blog if (isset($_POST['activation'])) { $customer_args['metadata']['activation'] = $_POST['activation']; } Stripe_InvoiceItem::create($customer_args); } catch (Exception $e) { wp_mail(get_blog_option($blog_id, 'admin_email'), __('Error charging setup fee. Attention required!', 'psts'), sprintf(__('An error occurred while charging a setup fee of %1$s to Stripe customer %2$s. You will need to manually process this amount.', 'psts'), $psts->format_currency($currency, $setup_fee), $customer_id)); } } // Create/update subscription try { $result = false; $sub = false; // Brand new blog... if (empty($blog_id)) { $result = $c->subscriptions->create($args); } else { $customer_data = self::get_customer_data($blog_id); try { $sub = $c->subscriptions->retrieve($customer_data->subscription_id); $sub_id = $sub->id; $prev_plan = $sub->plan->id; $sub->plan = isset($args['plan']) ? $args['plan'] : $sub->plan; $changed_plan = $sub->plan; $sub->prorate = isset($args['prorate']) ? $args['prorate'] : $sub->prorate; if (isset($args['coupon'])) { $sub->coupon = $args['coupon']; } if (isset($args['trial_end'])) { $sub->trial_end = $args['trial_end']; } $sub->metadata->period = $args['metadata']['period']; $sub->metadata->level = $args['metadata']['level']; if (isset($args['metadata']['activation'])) { $sub->metadata->activation = $args['metadata']['activation']; } else { $activation_key = ProSites_Helper_ProSite::get_activation_key($blog_id); if (!empty($activation_key)) { $sub->metadata->activation = $activation_key; } } $sub->metadata->blog_id = $blog_id; if (isset($args['metadata']['domain'])) { $sub->metadata->domain = $args['metadata']['domain']; } // Apply tax? if ($tax_object->apply_tax) { $sub->tax_percent = $tax_object->tax_rate * 100; $sub->metadata->tax_evidence = $evidence_string; } $sub->save(); // As per Stripe API, to charge immediately, apply an invoice now if ($prev_plan != $changed_plan) { $customer_args = array('customer' => $customer_id, 'subscription' => $sub_id, 'metadata' => array('plan_change' => 'yes')); $invoice = Stripe_Invoice::create($customer_args); $invoice = $invoice->pay(); $plan_parts = explode('_', $changed_plan); $new_period = array_pop($plan_parts); $new_level = array_pop($plan_parts); $plan_parts = explode('_', $prev_plan); $prev_period = array_pop($plan_parts); $prev_level = array_pop($plan_parts); $updated = array('render' => true, 'blog_id' => $blog_id, 'level' => $new_level, 'period' => $new_period, 'prev_level' => $prev_level, 'prev_period' => $prev_period); ProSites_Helper_Session::session('plan_updated', $updated); } } catch (Exception $e) { // Fall through... } // Additional blog if (empty($sub)) { $args['metadata']['blog_id'] = $blog_id; if (!isset($args['metadata']['activation'])) { $activation_key = ProSites_Helper_ProSite::get_activation_key($blog_id); if (!empty($activation_key)) { $args['metadata']['activation'] = $activation_key; } } $result = $c->subscriptions->create($args); } // This one is now deprecated // $result = $c->updateSubscription( $args ); } // Capture success as soon as we can! if (!empty($result)) { $sub_id = $result->id; $plan = $result->plan; $plan_parts = explode('_', $plan->id); $period = array_pop($plan_parts); $level = array_pop($plan_parts); $trial = isset($plan->status) && 'trialing' == $plan->status ? true : false; $expire = $trial ? $plan->trial_end : $result->current_period_end; $result = ProSites_Helper_Registration::activate_blog($activation_key, $trial, $period, $level, $expire); $blog_id = $result['blog_id']; if (isset($process_data['new_blog_details'])) { ProSites_Helper_Session::session(array('new_blog_details', 'blog_id'), $blog_id); ProSites_Helper_Session::session(array('new_blog_details', 'payment_success'), true); } else { ProSites_Helper_Session::session('upgrade_blog_details', array()); ProSites_Helper_Session::session(array('upgrade_blog_details', 'blog_id'), $blog_id); ProSites_Helper_Session::session(array('upgrade_blog_details', 'level'), $level); ProSites_Helper_Session::session(array('upgrade_blog_details', 'period'), $period); ProSites_Helper_Session::session(array('upgrade_blog_details', 'payment_success'), true); } self::set_customer_data($blog_id, $customer_id, $sub_id); } if ($current_plan = self::get_current_plan($blog_id)) { list($current_plan_level, $current_plan_period) = explode('_', $current_plan); } //Extend the Blog Subscription $old_expire = $psts->get_expire($blog_id); $new_expire = $old_expire && $old_expire > time() ? $old_expire : false; $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $initAmount, $new_expire, false); //$psts->email_notification( $blog_id, 'receipt' ); if (isset($current_plan_level)) { if ($current_plan_level > $_POST['level']) { $psts->record_stat($blog_id, 'upgrade'); } else { $psts->record_stat($blog_id, 'modify'); } } else { $psts->record_stat($blog_id, 'signup'); } // Update the sub with the new blog id (old subscriptions will update later). if (!empty($blog_id)) { $sub = $c->subscriptions->retrieve($sub_id); $sub->metadata->blog_id = $blog_id; $sub->save(); } } catch (Exception $e) { $body = $e->getJsonBody(); $error = $body['error']; $psts->errors->add('general', $error['message']); return; } } else { // Not a subscription, this is a one of payment, charged for 1 term try { if (!empty($blog_id)) { $initAmount = $psts->calc_upgrade_cost($blog_id, $_POST['level'], $_POST['period'], $initAmount); //If activation key is empty $activation_key = !empty($activation_key) ? $activation_key : ProSites_Helper_ProSite::get_activation_key($blog_id); } if ($tax_object->apply_tax) { $amount = $initAmount + $initAmount * $tax_object->tax_rate; $desc += sprintf(__('(includes tax of %s%% [%s])', 'psts'), $tax_object->tax_rate * 100, $tax_object->country); } else { $amount = $initAmount; } $customer_args = array('customer' => $customer_id, 'amount' => $amount * 100, 'currency' => $currency, 'description' => $desc, 'metadata' => array('domain' => !empty($domain) ? $domain : '', 'period' => $_POST['period'], 'level' => $_POST['level'])); if ($tax_object->apply_tax) { $customer_args['metadata']['tax_evidence'] = $evidence_string; } if (!$domain) { unset($customer_args['metadata']['domain']); } // new blog if (isset($_POST['activation'])) { $customer_args['metadata']['activation'] = $_POST['activation']; } /** * 1 off charge of not trialing, but if trialing, just send a zero-dollar invoice */ if (empty($trial_days) || 0 == $customer_args['amount']) { $result = Stripe_Charge::create($customer_args); } else { $result = Stripe_InvoiceItem::create($customer_args); } // Capture success as soon as we can! if ($result) { $period = (int) $_POST['period']; $level = (int) $_POST['level']; $signup_details = ProSites_Helper_Registration::activate_blog($activation_key, false, $period, $level); $blog_id = $signup_details['blog_id']; if (isset($process_data['new_blog_details'])) { ProSites_Helper_Session::session(array('new_blog_details', 'blog_id'), $blog_id); ProSites_Helper_Session::session(array('new_blog_details', 'payment_success'), true); } self::set_customer_data($blog_id, $customer_id, $result->id); } if ($current_plan = self::get_current_plan($blog_id)) { list($current_plan_level, $current_plan_period) = explode('_', $current_plan); } $old_expire = $psts->get_expire($blog_id); $new_expire = $old_expire && $old_expire > time() ? $old_expire : false; $psts->extend($blog_id, $_POST['period'], self::get_slug(), $_POST['level'], $initAmount, $new_expire, false); //$psts->email_notification( $blog_id, 'receipt' ); if (isset($current_plan_level)) { if ($current_plan_level > $_POST['level']) { $psts->record_stat($blog_id, 'upgrade'); } else { $psts->record_stat($blog_id, 'modify'); } } else { $psts->record_stat($blog_id, 'signup'); } } catch (Stripe_CardError $e) { $body = $e->getJsonBody(); $err = $body['error']; $psts->errors->add('general', $e['message']); } catch (Exception $e) { $psts->errors->add('general', __('An unknown error occurred while processing your payment. Please try again.', 'psts')); } } //delete the temporary coupon code if ($cp_code) { try { $cpn = Stripe_Coupon::retrieve($cp_code); $cpn->delete(); } catch (Exception $e) { wp_mail(get_blog_option($blog_id, 'admin_email'), __('Error deleting temporary Stripe coupon code. Attention required!.', 'psts'), sprintf(__('An error occurred when attempting to delete temporary Stripe coupon code %1$s. You will need to manually delete this coupon via your Stripe account.', 'psts'), $cp_code)); } $psts->use_coupon($process_data['COUPON_CODE'], $blog_id, $domain); } if ($new || $psts->is_blog_canceled($blog_id)) { // Added for affiliate system link if ($recurring) { $psts->log_action($blog_id, sprintf(__('User creating new subscription via CC: Subscription created (%1$s) - Customer ID: %2$s', 'psts'), $desc, $customer_id), $domain); } else { $psts->log_action($blog_id, sprintf(__('User completed new payment via CC: Site created/extended (%1$s) - Customer ID: %2$s', 'psts'), $desc, $customer_id), $domain); } do_action('supporter_payment_processed', $blog_id, $paymentAmount, $_POST['period'], $_POST['level']); } else { $psts->log_action($blog_id, sprintf(__('User modifying subscription via CC: Plan changed to (%1$s) - %2$s', 'psts'), $desc, $customer_id), $domain); } //display GA ecommerce in footer $psts->create_ga_ecommerce($blog_id, $_POST['period'], $initAmount, $_POST['level'], $site_name, $domain); if (!empty($blog_id)) { update_blog_option($blog_id, 'psts_stripe_canceled', 0); /* some times there is a lag receiving webhooks from Stripe. we want to be able to check for that and display an appropriate message to the customer (e.g. there are changes pending to your account) */ update_blog_option($blog_id, 'psts_stripe_waiting', 1); } else { if (isset($process_data['activation_key'])) { //Update signup meta $key = $process_data['activation_key']; $signup_meta = ''; $signup_meta = $psts->get_signup_meta($key); $signup_meta['psts_stripe_canceled'] = 0; $signup_meta['psts_stripe_waiting'] = 1; $psts->update_signup_meta($signup_meta, $key); } } update_blog_option($blog_id, 'psts_stripe_waiting', 1); if (empty(self::$complete_message)) { // Message is redundant now, but still used as a flag. self::$complete_message = __('Your payment was successfully recorded! You should be receiving an email receipt shortly.', 'psts'); } } catch (Exception $e) { $psts->errors->add('general', $e->getMessage()); } } }
public function updatePlan(User $user, Plan $plan, $coupon_id = null) { $customer_id = $user->getProfile() ? $user->getProfile()->getCustomerId() : null; $new_plan_id = $plan->getId(); if ($customer_id) { $customer = \Stripe_Customer::retrieve($customer_id); if ($coupon_id && $this->getCuponById($coupon_id)) { $customer->coupon = $coupon_id; $customer->save(); } if ($new_plan_id !== 1) { $currentSubscription = $this->getCurrentSubscription($user, $customer); $subscription = $customer->subscriptions->retrieve($currentSubscription['id']); $subscription->plan = $new_plan_id; $proration_date = new \DateTime(); $subscription->proration_date = $proration_date->getTimestamp(); $subscription->tax_percent = 7; $subscription->save(); $current_plan_id = $user->getCurrentPlan()->getPlan()->getId(); if ($current_plan_id != 1) { $invoice = \Stripe_Invoice::create(array("customer" => $customer_id, "subscription" => $subscription['id'])); $result = $invoice->pay(); if ($result->paid != true) { $invoice->closed = true; $invoice->save(); $customer->updateSubscription(array('plan' => $current_plan_id, 'prorate' => false, 'application_fee_percent' => 4, 'tax_percent' => 7)); } } } } else { //Inscribir al Usuario en el Plan Free por primera vez $customer = \Stripe_Customer::create(array("plan" => $new_plan_id, "email" => $user->getEmail())); $customer_id = $customer->id; } //Update Current Plan if (is_array($customer->subscriptions->data)) { foreach ($customer->subscriptions->data as $data) { if ($data->status == 'active') { $dateStart = $data->current_period_start; $dateEnd = $data->current_period_end; break; } } } else { $dateStart = $customer->subscriptions->data->current_period_start; $dateEnd = $customer->subscriptions->data->current_period_end; } $dateTimeStart = new \DateTime(); $dateTimeStart->setTimestamp($dateStart); $dateTimeEnd = new \DateTime(); $dateTimeEnd->setTimestamp($dateEnd); $userPlan = new UserPlan($user, $plan); $userPlan->setDateStart($dateTimeStart); $userPlan->setDateEnd($dateTimeEnd); $user->getProfile()->setCustomerId($customer_id); $user->addPlan($userPlan); $this->saveData($user); return $plan; }
public function buySubscription($userDetail, $token, $plan, $userEmail) { try { $secret_key = config_item('stripe_secret'); Stripe::setApiKey($secret_key); $description = sprintf("One year subscription fee for %s", $plan); $customerOption = array("card" => $token, "email" => $userEmail); $customer = Stripe_Customer::create($customerOption); // echo "Customer Information: <br>"; // $this->util->echoObject($customer); $subscriptionOption = array("plan" => $plan); $subscriptionInfo = $customer->subscriptions->create($subscriptionOption); // echo "Customer Information: <br>"; // $this->util->echoObject($subscriptionInfo); $stripeCustomerID = $customer->id; $amount = $subscriptionInfo->plan->amount; $currency = $subscriptionInfo->plan->currency; $discount = 0; $invoice_item = Stripe_InvoiceItem::create(array('customer' => $stripeCustomerID, 'amount' => $amount, 'currency' => $currency, 'description' => $description)); // echo "Invoice Item: <br>"; // $this->util->echoObject($invoice_item); $invoice = Stripe_Invoice::create(array('customer' => $stripeCustomerID)); // echo "Invoice: <br>"; // $this->util->echoObject($invoice); $invoice->pay(); if (!$invoice->paid) { return false; } $this->updateUserProfile($userDetail->ID, $stripeCustomerID, $plan, $subscriptionInfo->current_period_start, $subscriptionInfo->current_period_end, $amount, $currency, $discount, $subscriptionInfo->name, $subscriptionInfo->id); $order_no = $invoice->id; if ($order_no) { $pdf_html = $this->util->makeInvoicePDFContent($userDetail, $subscriptionInfo, $invoice, $order_no, $customer->sources->data[0]->last4, $discount); $this->load->library('dompdf_lib'); $pdf_content = $this->dompdf_lib->convert_html_to_pdf($pdf_html, $order_no, false); $file_name = $this->util->getEncryptedFileName($order_no); $this->util->uploadFileToServer($file_name, $pdf_content); /* Send invoice in mail */ $ci = get_instance(); $ci->load->library('email'); $ci->email->from(config_item('support_email'), 'Taxideals support service'); $list = array($userEmail); $ci->email->to($list); $this->email->reply_to($userEmail, ''); $ci->email->subject('New invoice email'); $ci->email->attach($_SERVER['DOCUMENT_ROOT'] . 'dev/invoices/' . $file_name . '.pdf'); $msg = "Dear customer,<br/><br/>"; $msg = $msg . "We are contacting you in regard to a new invoice that has been created on your account. You may find the invoice attached.<br/>"; $msg = $msg . "If you have questions, we're happy to help. "; $msg = $msg . "Please conntact us via email: <a href=\"mailto:support@taxideals.com.au\">Taxideals Support</a>.<br/>"; $msg = $msg . "<br/>Regards,<br/>The Taxideals team"; $ci->email->message($msg); $ci->email->send(); } return $order_no; } catch (Stripe_CardError $e) { $this->printError($e); return false; } catch (Stripe_InvalidRequestError $e) { $this->printError($e); return false; } catch (Stripe_AuthenticationError $e) { $this->printError($e); return false; } catch (Stripe_ApiConnectionError $e) { $this->printError($e); return false; } catch (Stripe_Error $e) { $this->printError($e); return false; } catch (Exception $e) { $this->printError($e); return false; } catch (ErrorException $e) { $this->printError($e); return false; } }
/** * Process stripe checkout submission * * @access public * @since 1.0 * @return void */ function edds_process_stripe_payment($purchase_data) { global $edd_options; if (!class_exists('Stripe')) { require_once EDDS_PLUGIN_DIR . '/Stripe/Stripe.php'; } if (edd_is_test_mode()) { $secret_key = trim($edd_options['test_secret_key']); } else { $secret_key = trim($edd_options['live_secret_key']); } $purchase_summary = edd_get_purchase_summary($purchase_data, false); // make sure we don't have any left over errors present edd_clear_errors(); if (!isset($_POST['edd_stripe_token'])) { // check for fallback mode if (isset($edd_options['stripe_js_fallback'])) { if (!isset($_POST['card_name']) || strlen(trim($_POST['card_name'])) == 0) { edd_set_error('no_card_name', __('Please enter a name for the credit card.', 'edds')); } if (!isset($_POST['card_number']) || strlen(trim($_POST['card_number'])) == 0) { edd_set_error('no_card_number', __('Please enter a credit card number.', 'edds')); } if (!isset($_POST['card_cvc']) || strlen(trim($_POST['card_cvc'])) == 0) { edd_set_error('no_card_cvc', __('Please enter a CVC/CVV for the credit card.', 'edds')); } if (!isset($_POST['card_exp_month']) || strlen(trim($_POST['card_exp_month'])) == 0) { edd_set_error('no_card_exp_month', __('Please enter a expiration month.', 'edds')); } if (!isset($_POST['card_exp_year']) || strlen(trim($_POST['card_exp_year'])) == 0) { edd_set_error('no_card_exp_year', __('Please enter a expiration year.', 'edds')); } $card_data = array('number' => $purchase_data['card_info']['card_number'], 'name' => $purchase_data['card_info']['card_name'], 'exp_month' => $purchase_data['card_info']['card_exp_month'], 'exp_year' => $purchase_data['card_info']['card_exp_year'], 'cvc' => $purchase_data['card_info']['card_cvc'], 'address_line1' => $purchase_data['card_info']['card_address'], 'address_line2' => $purchase_data['card_info']['card_address_2'], 'address_city' => $purchase_data['card_info']['card_city'], 'address_zip' => $purchase_data['card_info']['card_zip'], 'address_state' => $purchase_data['card_info']['card_state'], 'address_country' => $purchase_data['card_info']['card_country']); } else { // no Stripe token edd_set_error('no_token', __('Missing Stripe token. Please contact support.', 'edds')); edd_record_gateway_error(__('Missing Stripe Token', 'edds'), __('A Stripe token failed to be generated. Please check Stripe logs for more information', ' edds')); } } else { $card_data = $_POST['edd_stripe_token']; } $errors = edd_get_errors(); if (!$errors) { try { Stripe::setApiKey($secret_key); // setup the payment details $payment_data = array('price' => $purchase_data['price'], 'date' => $purchase_data['date'], 'user_email' => $purchase_data['user_email'], 'purchase_key' => $purchase_data['purchase_key'], 'currency' => edd_get_currency(), 'downloads' => $purchase_data['downloads'], 'cart_details' => $purchase_data['cart_details'], 'user_info' => $purchase_data['user_info'], 'status' => 'pending', 'gateway' => 'stripe'); $customer_exists = false; if (is_user_logged_in()) { $user = get_user_by('email', $purchase_data['user_email']); if ($user) { $customer_id = get_user_meta($user->ID, edd_stripe_get_customer_key(), true); if ($customer_id) { $customer_exists = true; try { // Update the customer to ensure their card data is up to date $cu = Stripe_Customer::retrieve($customer_id); if (isset($cu->deleted) && $cu->deleted) { // This customer was deleted $customer_exists = false; } else { $cu->card = $card_data; $cu->save(); } // No customer found } catch (Exception $e) { $customer_exists = false; } } } } if (!$customer_exists) { // Create a customer first so we can retrieve them later for future payments $customer = Stripe_Customer::create(array('description' => $purchase_data['user_email'], 'email' => $purchase_data['user_email'], 'card' => $card_data)); $customer_id = is_array($customer) ? $customer['id'] : $customer->id; if (is_user_logged_in()) { update_user_meta($user->ID, edd_stripe_get_customer_key(), $customer_id); } } if (edds_is_recurring_purchase($purchase_data) && (!empty($customer) || $customer_exists)) { // Process a recurring subscription purchase $cu = Stripe_Customer::retrieve($customer_id); /********************************************************** * Taxes, fees, and discounts have to be handled differently * with recurring subscriptions, so each is added as an * invoice item and then charged as one time items **********************************************************/ $invoice_items = array(); $needs_invoiced = false; if ($purchase_data['tax'] > 0 && !edd_prices_include_tax()) { if (edds_is_zero_decimal_currency()) { $tax = $purchase_data['tax']; } else { $tax = $purchase_data['tax'] * 100; } $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $tax, 'currency' => edd_get_currency(), 'description' => sprintf(__('Sales tax for order %s', 'edds'), $purchase_data['purchase_key']))); if (!empty($invoice->id)) { $invoice_items[] = $invoice->id; } $needs_invoiced = true; } if (!empty($purchase_data['fees'])) { foreach ($purchase_data['fees'] as $fee) { if (edds_is_zero_decimal_currency()) { $fee_amount = $fee['amount']; } else { $fee_amount = $fee['amount'] * 100; } $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $fee_amount, 'currency' => edd_get_currency(), 'description' => $fee['label'])); if (!empty($invoice->id)) { $invoice_items[] = $invoice->id; } } $needs_invoiced = true; } if ($purchase_data['discount'] > 0) { if (edds_is_zero_decimal_currency()) { $discount_amount = $purchase_data['discount']; } else { $discount_amount = $purchase_data['discount'] * 100; } $invoice = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $discount_amount * -1, 'currency' => edd_get_currency(), 'description' => $purchase_data['user_info']['discount'])); if (!empty($invoice->id)) { $invoice_items[] = $invoice->id; } $needs_invoiced = true; } try { $plan_id = edds_get_plan_id($purchase_data); // record the pending payment $payment = edd_insert_payment($payment_data); set_transient('_edd_recurring_payment_' . $payment, '1', DAY_IN_SECONDS); // Store the parent payment ID in the user meta EDD_Recurring_Customer::set_customer_payment_id($user->ID, $payment); // Update the customer's subscription in Stripe $customer_response = $cu->updateSubscription(array('plan' => $plan_id)); // Set user as subscriber EDD_Recurring_Customer::set_as_subscriber($user->ID); // store the customer recurring ID EDD_Recurring_Customer::set_customer_id($user->ID, $customer_id); // Set the customer status EDD_Recurring_Customer::set_customer_status($user->ID, 'active'); // Calculate the customer's new expiration date $new_expiration = EDD_Recurring_Customer::calc_user_expiration($user->ID, $payment); // Set the customer's new expiration date EDD_Recurring_Customer::set_customer_expiration($user->ID, $new_expiration); } catch (Stripe_CardError $e) { $body = $e->getJsonBody(); $err = $body['error']; if (isset($err['message'])) { edd_set_error('payment_error', $err['message']); } else { edd_set_error('payment_error', __('There was an error processing your payment, please ensure you have entered your card number correctly.', 'edds')); } edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error while processing a Stripe payment. Payment data: %s', ' edds'), json_encode($err)), 0); } catch (Stripe_ApiConnectionError $e) { $body = $e->getJsonBody(); $err = $body['error']; edd_set_error('payment_error', __('There was an error processing your payment (Stripe\'s API is down), please try again', 'edds')); edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error processing your payment (Stripe\'s API was down). Error: %s', 'edds'), json_encode($err['message'])), 0); } catch (Stripe_InvalidRequestError $e) { $body = $e->getJsonBody(); $err = $body['error']; // Bad Request of some sort. Maybe Christoff was here ;) if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('request_error', sprintf(__('The Stripe API request was invalid, please try again. Error: %s', 'edds'), json_encode($err['message']))); } } catch (Stripe_ApiError $e) { $body = $e->getJsonBody(); $err = $body['error']; if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds')); } edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error with Stripe\'s API: ', 'edds'), json_encode($err['message'])), 0); } catch (Stripe_AuthenticationError $e) { $body = $e->getJsonBody(); $err = $body['error']; // Authentication error. Stripe keys in settings are bad. if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('api_error', __('The API keys entered in settings are incorrect', 'edds')); } } catch (Stripe_Error $e) { $body = $e->getJsonBody(); $err = $body['error']; // generic stripe error if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('api_error', __('Something went wrong.', 'edds')); } } catch (Exception $e) { // some sort of other error $body = $e->getJsonBody(); $err = $body['error']; if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('api_error', __('Something went wrong.', 'edds')); } } if (!empty($err)) { // Delete any invoice items we created for fees, taxes, and other foreach ($invoice_items as $invoice) { $ii = Stripe_InvoiceItem::retrieve($invoice); $ii->delete(); } edd_send_back_to_checkout('?payment-mode=stripe'); } } elseif (!empty($customer) || $customer_exists) { // Process a normal one-time charge purchase if (!isset($edd_options['stripe_preapprove_only'])) { if (edds_is_zero_decimal_currency()) { $amount = $purchase_data['price']; } else { $amount = $purchase_data['price'] * 100; } $charge = Stripe_Charge::create(array("amount" => $amount, "currency" => edd_get_currency(), "customer" => $customer_id, "description" => html_entity_decode($purchase_summary, ENT_COMPAT, 'UTF-8'), 'statement_description' => substr($purchase_summary, 0, 15), 'metadata' => array('email' => $purchase_data['user_info']['email']))); } // record the pending payment $payment = edd_insert_payment($payment_data); } else { edd_record_gateway_error(__('Customer Creation Failed', 'edds'), sprintf(__('Customer creation failed while processing a payment. Payment Data: %s', ' edds'), json_encode($payment_data)), $payment); } if ($payment && (!empty($customer_id) || !empty($charge))) { if (!empty($needs_invoiced)) { try { // Create the invoice containing taxes / discounts / fees $invoice = Stripe_Invoice::create(array('customer' => $customer_id)); $invoice = $invoice->pay(); } catch (Exception $e) { // If there is nothing to pay, it just means the invoice item was taken care of with the subscription payment } } if (isset($edd_options['stripe_preapprove_only'])) { edd_update_payment_status($payment, 'preapproval'); add_post_meta($payment, '_edds_stripe_customer_id', $customer_id); } else { edd_update_payment_status($payment, 'publish'); } // You should be using Stripe's API here to retrieve the invoice then confirming it's been paid if (!empty($charge)) { edd_insert_payment_note($payment, 'Stripe Charge ID: ' . $charge->id); if (function_exists('edd_set_payment_transaction_id')) { edd_set_payment_transaction_id($payment, $charge->id); } } elseif (!empty($customer_id)) { edd_insert_payment_note($payment, 'Stripe Customer ID: ' . $customer_id); } edd_empty_cart(); edd_send_to_success_page(); } else { edd_set_error('payment_not_recorded', __('Your payment could not be recorded, please contact the site administrator.', 'edds')); // if errors are present, send the user back to the purchase page so they can be corrected edd_send_back_to_checkout('?payment-mode=stripe'); } } catch (Stripe_CardError $e) { $body = $e->getJsonBody(); $err = $body['error']; if (isset($err['message'])) { edd_set_error('payment_error', $err['message']); } else { edd_set_error('payment_error', __('There was an error processing your payment, please ensure you have entered your card number correctly.', 'edds')); } edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error while processing a Stripe payment. Payment data: %s', ' edds'), json_encode($err)), 0); edd_send_back_to_checkout('?payment-mode=stripe'); } catch (Stripe_ApiConnectionError $e) { $body = $e->getJsonBody(); $err = $body['error']; edd_set_error('payment_error', __('There was an error processing your payment (Stripe\'s API is down), please try again', 'edds')); edd_record_gateway_error(__('Stripe Error', 'edds'), sprintf(__('There was an error processing your payment (Stripe\'s API was down). Error: %s', 'edds'), json_encode($err['message'])), 0); edd_send_back_to_checkout('?payment-mode=stripe'); } catch (Stripe_InvalidRequestError $e) { $body = $e->getJsonBody(); $err = $body['error']; // Bad Request of some sort. Maybe Christoff was here ;) if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds')); } edd_send_back_to_checkout('?payment-mode=stripe'); } catch (Stripe_ApiError $e) { $body = $e->getJsonBody(); $err = $body['error']; if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('request_error', __('The Stripe API request was invalid, please try again', 'edds')); } edd_set_error('request_error', sprintf(__('The Stripe API request was invalid, please try again. Error: %s', 'edds'), json_encode($err['message']))); edd_send_back_to_checkout('?payment-mode=stripe'); } catch (Stripe_AuthenticationError $e) { $body = $e->getJsonBody(); $err = $body['error']; // Authentication error. Stripe keys in settings are bad. if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('api_error', __('The API keys entered in settings are incorrect', 'edds')); } edd_send_back_to_checkout('?payment-mode=stripe'); } catch (Stripe_Error $e) { $body = $e->getJsonBody(); $err = $body['error']; // generic stripe error if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('api_error', __('Something went wrong.', 'edds')); } edd_send_back_to_checkout('?payment-mode=stripe'); } catch (Exception $e) { // some sort of other error $body = $e->getJsonBody(); $err = $body['error']; if (isset($err['message'])) { edd_set_error('request_error', $err['message']); } else { edd_set_error('api_error', __('Something went wrong.', 'edds')); } edd_send_back_to_checkout('?payment-mode=stripe'); } } else { edd_send_back_to_checkout('?payment-mode=stripe'); } }
public function send_gift_manual() { global $wpdb, $ntm_mail; if (isset($_POST['send_gift'])) { $option = get_option('giftbit'); if ($option['amount'] >= $_POST['gift_amount']) { $this->fa_lead_options = get_option('fa_lead_settings'); Stripe::setApiKey($this->fa_lead_options['api_key']); Stripe::setAPIVersion("2015-07-13"); $customer_id = get_user_meta(get_blog_option(get_current_blog_id(), 'agent_id'), "pmpro_stripe_customerid"); $amount = $this->fa_lead_options['admin_fee'] * 100; $giftAmount = $this->fa_lead_options['init_gift']; $invoice_item = Stripe_InvoiceItem::create(array('customer' => $customer_id, 'amount' => $this->fa_lead_options['admin_fee'], 'currency' => 'usd', 'description' => 'One-time setup fee')); $invoice = Stripe_Invoice::create(array('customer' => $customer_id)); $result = $invoice->pay(); if (isset($result->object) && $result->object == 'invoice') { $data = array('endorser_id' => $_POST['endorser_id'], 'amout' => $_POST['gift_amount'], 'agent_id' => get_current_user_id(), 'created' => date("Y-m-d H:i:s")); $wpdb->insert($wpdb->prefix . "gift_transaction", $data); $gift_id = $wpdb->insert_id; $ntm_mail->send_gift_mail('get_manualgift_mail', $_POST['endorser_id'], $gift_id); $option['amount'] = $option['amount'] - $_POST['gift_amount']; update_option("giftbit", $option); $message = "Gift send successfully!!"; } else { $message = "Error when payment"; } } else { $message = "Error! Insufficient balance!"; } } //print_r(get_users(array('role'=>'endorser'))); ?> <script> jQuery(document).ready(function(){ jQuery("#gift_amount").change(function(){ if(jQuery("#gift_amount").val() <= jQuery("#poststuff").data('amount')) jQuery("#send_gift").show(); else { alert("Insufficient balance"); jQuery("#send_gift").hide(); } }); }); </script> <div data-amount="<?php echo get_option('giftbit')['amount']; ?> " id="poststuff" class="wrap"> <h2>Send Gift By Manual</h2> <?php if (isset($message)) { ?> <div id="message" class="updated"><p><?php echo $message; ?> </p></div> <?php } ?> <div class="postbox"> <div class="inside group"> <form name="myform" method="post" > <table id="country" class="form-table"> <tr> <th scope="row"><label for="blogname">Endorser</label></th> <td> <select class="regular-text" name="endorser_id"> <option value="">Select Endorser</option> <?php foreach (get_users(array('role' => 'endorser')) as $res) { ?> <option value="<?php _e($res->data->ID); ?> "><?php _e($res->data->user_login . ' - ' . $res->data->user_email); ?> </option> <?php } ?> </select> </td> </tr> <tr> <th scope="row"><label for="blogname">Gift Amount</label></th> <td> <select class="regular-text" id="gift_amount" name="gift_amount"> <option value="5">5$</option> <option value="10">10$</option> <option value="25">25$</option> <option value="50">50$</option> <option value="100">100$</option> <option value="150">150$</option> <option value="200">200$</option> </select> </td> </tr> </table> <p class="submit"> <input style="display:none;" id="send_gift" name="send_gift" class="button-primary seeker_btn" value="<?php _e('Save Changes'); ?> " type="submit" /> </p> </form> </div> </div> </div> <?php }
/** * Create a new Stripe invoice * @param mixed $cus_attr * @param array $data * @return Stripe_Invoice|false */ public function createInvoice($cus_attr = null, $data = array()) { $fields = array('application_fee', 'description', 'metadata', 'subscription'); try { foreach ($data as $key => $value) { if (!in_array($key, $fields)) { $data[$key] = ''; } } $data = array_filter($data); $customer = new StripeCustomer($cus_attr); $data['customer'] = $customer->getCustomerAccount()->id; return Stripe_Invoice::create($data, $this->access_token); } catch (Exception $ex) { $this->log($ex); return false; } }