public function do_charge()
 {
     if (wp_verify_nonce($_POST['wp-simple-pay-pro-nonce'], 'charge_card')) {
         global $sc_options;
         $query_args = array();
         // Set redirect
         $redirect = $_POST['sc-redirect'];
         $fail_redirect = $_POST['sc-redirect-fail'];
         $failed = null;
         $message = '';
         // Get the credit card details submitted by the form
         $token = $_POST['stripeToken'];
         $amount = $_POST['sc-amount'];
         $description = $_POST['sc-description'];
         $store_name = $_POST['sc-name'];
         $currency = $_POST['sc-currency'];
         $details_placement = $_POST['sc-details-placement'];
         $charge = null;
         $sub = isset($_POST['sc_sub_id']);
         $interval = isset($_POST['sc_sub_interval']) ? $_POST['sc_sub_interval'] : 'month';
         $interval_count = isset($_POST['sc_sub_interval_count']) ? $_POST['sc_sub_interval_count'] : 1;
         $statement_description = isset($_POST['sc_sub_statement_description']) ? $_POST['sc_sub_statement_description'] : '';
         $setup_fee = isset($_POST['sc_sub_setup_fee']) ? $_POST['sc_sub_setup_fee'] : 0;
         $coupon = isset($_POST['sc_coup_coupon_code']) ? $_POST['sc_coup_coupon_code'] : '';
         $test_mode = isset($_POST['sc_test_mode']) ? $_POST['sc_test_mode'] : 'false';
         if ($sub) {
             $sub = !empty($_POST['sc_sub_id']) ? $_POST['sc_sub_id'] : 'custom';
         }
         Stripe_Checkout_Functions::set_key($test_mode);
         $meta = array();
         if (!empty($setup_fee)) {
             $meta['Setup Fee'] = Stripe_Checkout_Misc::to_formatted_amount($setup_fee, $currency);
         }
         $meta = apply_filters('sc_meta_values', $meta);
         try {
             if ($sub == 'custom') {
                 $timestamp = time();
                 $plan_id = $_POST['stripeEmail'] . '_' . $amount . '_' . $timestamp;
                 $name = __('Subscription:', 'sc_sub') . ' ' . Stripe_Checkout_Misc::to_formatted_amount($amount, $currency) . ' ' . strtoupper($currency) . '/' . $interval;
                 // Create a plan
                 $plan_args = array('amount' => $amount, 'interval' => $interval, 'name' => $name, 'currency' => $currency, 'id' => $plan_id, 'interval_count' => $interval_count);
                 if (!empty($statement_description)) {
                     $plan_args['statement_descriptor'] = $statement_description;
                 }
                 $new_plan = \Stripe\Plan::create($plan_args);
                 // Create a customer and charge
                 $new_customer = \Stripe\Customer::create(array('email' => $_POST['stripeEmail'], 'card' => $token, 'plan' => $plan_id, 'metadata' => $meta, 'account_balance' => $setup_fee));
             } else {
                 // Create new customer
                 $cust_args = array('email' => $_POST['stripeEmail'], 'card' => $token, 'plan' => $sub, 'metadata' => $meta, 'account_balance' => $setup_fee);
                 if (!empty($coupon)) {
                     $cust_args['coupon'] = $coupon;
                 }
                 $new_customer = \Stripe\Customer::create($cust_args);
                 // Set currency based on sub
                 $plan = \Stripe\Plan::retrieve($sub);
                 //echo $subscription . '<Br>';
                 $currency = strtoupper($plan->currency);
             }
             // We want to add the meta data and description to the actual charge so that users can still view the meta sent with a subscription + custom fields
             // the same way that they would normally view it without subscriptions installed.
             // We need the steps below to do this
             // First we get the latest invoice based on the customer ID
             $invoice = \Stripe\Invoice::all(array('customer' => $new_customer->id, 'limit' => 1));
             // If this is a trial we need to skip this part since a charge is not made
             $trial = $invoice->data[0]->lines->data[0]->plan->trial_period_days;
             if (empty($trial) || !empty($setup_fee)) {
                 // Now that we have the invoice object we can get the charge ID
                 $inv_charge = $invoice->data[0]->charge;
                 // Finally, with the charge ID we can update the specific charge and inject our meta data sent from Stripe Custom Fields
                 $ch = \Stripe\Charge::retrieve($inv_charge);
                 $charge = $ch;
                 if (!empty($meta)) {
                     $ch->metadata = $meta;
                 }
                 if (!empty($description)) {
                     $ch->description = $description;
                 }
                 $ch->save();
                 $query_args = array('charge' => $ch->id, 'store_name' => urlencode($store_name));
                 $failed = false;
             } else {
                 $sub_id = $invoice->data[0]->subscription;
                 if (!empty($description)) {
                     $customer = \Stripe\Customer::retrieve($new_customer->id);
                     $subscription = $customer->subscriptions->retrieve($sub_id);
                     $subscription->metadata = array('product' => $description);
                     $subscription->save();
                 }
                 $query_args = array('cust_id' => $new_customer->id, 'sub_id' => $sub_id, 'store_name' => urlencode($store_name));
                 $failed = false;
             }
         } catch (Exception $e) {
             // Something else happened, completely unrelated to Stripe
             $redirect = $fail_redirect;
             $failed = true;
             $e = $e->getJsonBody();
             $query_args = array('sub' => true, 'error_code' => $e['error']['type'], 'charge_failed' => true);
         }
         unset($_POST['stripeToken']);
         do_action('sc_redirect_before');
         if ($test_mode == 'true') {
             $query_args['test_mode'] = 'true';
         }
         if ('below' == $details_placement) {
             $query_args['details_placement'] = $details_placement;
         }
         if (!empty($trial) && empty($setup_fee)) {
             $query_args['trial'] = 1;
         }
         wp_redirect(esc_url_raw(add_query_arg(apply_filters('sc_redirect_args', $query_args, $charge), apply_filters('sc_redirect', $redirect, $failed))));
         exit;
     }
 }
Example #2
0
 /**
  * Gets info for an invoice.
  *
  * @return array|null
  */
 public function info()
 {
     if (!$this->id || !$this->stripe_customer) {
         return null;
     }
     if (!$this->stripe_invoice) {
         $this->stripe_invoice = Stripe_Invoice::retrieve($this->id);
         if ($this->stripe_customer->id != $this->stripe_invoice->customer) {
             return $this->stripe_invoice = null;
         }
     }
     if (!$this->stripe_invoice) {
         return null;
     }
     $discounts = array();
     if ($this->stripe_invoice->discount) {
         $discounts[] = array('coupon' => $this->stripe_invoice->discount->coupon->id, 'amount_off' => $this->stripe_invoice->discount->coupon->amount_off, 'percent_off' => $this->stripe_invoice->discount->coupon->percent_off, 'started_at' => date('Y-m-d H:i:s', $this->stripe_invoice->discount->start), 'ends_at' => $this->stripe_invoice->discount->end ? date('Y-m-d H:i:s', $this->stripe_invoice->discount->end) : null);
     }
     $items = array();
     foreach ($this->stripe_invoice->lines->data as $line) {
         $item = array('id' => $line->id, 'amount' => $line->amount, 'period_start' => null, 'period_end' => null, 'description' => $line->description, 'subscription_id' => 'subscription' == $line->type ? $line->id : $line->subscription, 'quantity' => $line->quantity);
         if ($line->period && $line->period->start) {
             $item['period_start'] = date('Y-m-d H:i:s', $line->period->start);
         }
         if ($line->period && $line->period->end) {
             $item['period_end'] = date('Y-m-d H:i:s', $line->period->end);
         }
         $items[] = $item;
     }
     return array('id' => $this->id, 'date' => date('Y-m-d H:i:s', $this->stripe_invoice->date), 'total' => $this->stripe_invoice->total, 'subtotal' => $this->stripe_invoice->subtotal, 'amount' => $this->stripe_invoice->amount_due, 'starting_balance' => $this->stripe_invoice->starting_balance, 'ending_balance' => $this->stripe_invoice->ending_balance, 'closed' => $this->stripe_invoice->closed, 'paid' => $this->stripe_invoice->paid, 'discounts' => $discounts, 'items' => $items);
 }
Example #3
0
 public function testUpcoming()
 {
     authorizeFromEnv();
     $customer = self::createTestCustomer();
     InvoiceItem::create(array('customer' => $customer->id, 'amount' => 0, 'currency' => 'usd'));
     $invoice = Invoice::upcoming(array('customer' => $customer->id));
     $this->assertEqual($invoice->customer, $customer->id);
     $this->assertEqual($invoice->attempted, false);
 }
Example #4
0
 /**
  * Customize Spark's new user registration logic.
  *
  * @return void
  */
 protected function customizeRegistration()
 {
     if (Spark::basedInEU()) {
         Spark::validateRegistrationsWith(function (Request $request, $withSubscription = false) {
             $userRules = ['name' => 'required|max:255', 'email' => 'required|email|unique:users', 'password' => 'required|confirmed|min:6', 'terms' => 'required|accepted'];
             $addressRules = ['street' => 'required', 'city' => 'required', 'zip' => 'required', 'country' => 'required', 'vat_id' => 'vat_number'];
             return $withSubscription ? array_merge($userRules, $addressRules) : $userRules;
         });
     }
     // Spark::validateSubscriptionsWith(function (Request $request) {
     //     return [
     //         'plan' => 'required',
     //         'terms' => 'required|accepted',
     //         'stripe_token' => 'required',
     //     ];
     // });
     // Spark::createUsersWith(function (Request $request) {
     //     // Return New User Instance...
     // });
     /**
      * To comply with the EU VAT regulations we need to pass
      * the user's address, IP and company name to stripe.
      * This data will also be used for the invoices.
      */
     if (Spark::basedInEU()) {
         Spark::createSubscriptionsWith(function (Request $request, $user, $subscription) {
             /**
              * Apply tax rate from the given country.
              * If a valid VAT ID is given, the VAT
              * rate will be set to 0.
              */
             $user->setTaxForCountry($request->country, $request->has('vat_id'));
             $subscription->create($request->stripe_token, ['email' => $user->email, 'description' => $user->name, 'metadata' => ['ip' => $request->getClientIp(), 'company' => $request->company, 'vat_id' => $request->vat_id, 'tax_percent' => $user->getTaxPercent()]]);
         });
     }
     /**
      * Apply the tax rate of the customer to the invoice
      * when swapping plans.
      */
     if (Spark::basedInEU()) {
         Spark::swapSubscriptionsWith(function (Request $request, $user) {
             $user->subscription($request->plan)->maintainTrial()->prorate()->swap();
             $customer = $user->subscription()->getStripeCustomer();
             \Stripe\Invoice::create(['customer' => $customer->id, 'tax_percent' => $customer->metadata->tax_percent], $user->getStripeKey())->pay();
         });
     }
 }
Example #5
0
 /**
  * Gets all invoices for a customer.
  *
  * @return array
  */
 public function invoices()
 {
     $this->info();
     if (!$this->stripe_customer) {
         return array();
     }
     $invoices = Stripe_Invoice::all(array('customer' => $this->id, 'limit' => 100));
     $invoices_array = array();
     foreach ($invoices->data as $invoice) {
         $invoices_array[] = $this->invoice($invoice);
     }
     return $invoices_array;
 }
 public function process_webhooks()
 {
     if (!isset($_GET['listener']) || strtolower($_GET['listener']) != 'stripe') {
         return;
     }
     // Ensure listener URL is not cached by W3TC
     if (!defined('DONOTCACHEPAGE')) {
         define('DONOTCACHEPAGE', true);
     }
     \Stripe\Stripe::setApiKey($this->secret_key);
     // retrieve the request's body and parse it as JSON
     $body = @file_get_contents('php://input');
     $event_json_id = json_decode($body);
     $expiration = '';
     // for extra security, retrieve from the Stripe API
     if (isset($event_json_id->id)) {
         $rcp_payments = new RCP_Payments();
         $event_id = $event_json_id->id;
         try {
             $event = \Stripe\Event::retrieve($event_id);
             $payment_event = $event->data->object;
             if (empty($payment_event->customer)) {
                 die('no customer attached');
             }
             // retrieve the customer who made this payment (only for subscriptions)
             $user = rcp_get_member_id_from_profile_id($payment_event->customer);
             if (empty($user)) {
                 // Grab the customer ID from the old meta keys
                 global $wpdb;
                 $user = $wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->usermeta} WHERE meta_key = '_rcp_stripe_user_id' AND meta_value = %s LIMIT 1", $payment_event->customer));
             }
             if (empty($user)) {
                 die('no user ID found');
             }
             $member = new RCP_Member($user);
             // check to confirm this is a stripe subscriber
             if ($member) {
                 if (!$member->get_subscription_id()) {
                     die('no subscription ID for member');
                 }
                 if ($event->type == 'charge.succeeded' || $event->type == 'invoice.payment_succeeded') {
                     // setup payment data
                     $payment_data = array('date' => date_i18n('Y-m-d g:i:s', $event->created), 'payment_type' => 'Credit Card', 'user_id' => $member->ID, 'amount' => '', 'transaction_id' => '');
                     if ($event->type == 'charge.succeeded') {
                         // Successful one-time payment
                         if (empty($payment_event->invoice)) {
                             $payment_data['amount'] = $payment_event->amount / rcp_stripe_get_currency_multiplier();
                             $payment_data['transaction_id'] = $payment_event->id;
                             // Successful subscription payment
                         } else {
                             $invoice = \Stripe\Invoice::retrieve($payment_event->invoice);
                             $payment_data['amount'] = $invoice->amount_due / rcp_stripe_get_currency_multiplier();
                             $payment_data['transaction_id'] = $payment_event->id;
                         }
                         // Successful subscription paid made with account credit where no charge is created
                     } elseif ($event->type == 'invoice.payment_succeeded' && empty($payment_event->charge)) {
                         $payment_data['amount'] = $payment_event->amount_due / rcp_stripe_get_currency_multiplier();
                         $payment_data['transaction_id'] = $payment_event->id;
                         $invoice = $payment_event;
                     }
                     if (!empty($payment_data['transaction_id']) && !$rcp_payments->payment_exists($payment_data['transaction_id'])) {
                         if (!empty($invoice->subscription)) {
                             $customer = \Stripe\Customer::retrieve($member->get_payment_profile_id());
                             $subscription = $customer->subscriptions->retrieve($invoice->subscription);
                             if (!empty($subscription)) {
                                 $expiration = date('Y-m-d 23:59:59', $subscription->current_period_end);
                                 $member->set_recurring();
                             }
                             $member->set_merchant_subscription_id($subscription->id);
                         }
                         $member->renew($member->is_recurring(), 'active', $expiration);
                         // These must be retrieved after the status is set to active in order for upgrades to work properly
                         $payment_data['subscription'] = $member->get_subscription_name();
                         $payment_data['subscription_key'] = $member->get_subscription_key();
                         // record this payment if it hasn't been recorded yet
                         $rcp_payments->insert($payment_data);
                         do_action('rcp_stripe_charge_succeeded', $user, $payment_data);
                         die('rcp_stripe_charge_succeeded action fired successfully');
                     } else {
                         die('duplicate payment found');
                     }
                 }
                 // failed payment
                 if ($event->type == 'charge.failed') {
                     do_action('rcp_stripe_charge_failed', $invoice);
                     die('rcp_stripe_charge_failed action fired successfully');
                 }
                 // Cancelled / failed subscription
                 if ($event->type == 'customer.subscription.deleted') {
                     if (!$member->just_upgraded()) {
                         $member->set_status('cancelled');
                         die('member cancelled successfully');
                     }
                 }
                 do_action('rcp_stripe_' . $event->type, $payment_event);
             }
         } catch (Exception $e) {
             // something failed
             die('PHP exception: ' . $e->getMessage());
         }
         die('1');
     }
     die('no event ID found');
 }
                <td><?php 
        echo $subscription->status;
        ?>
</td>
                <td><a href="<?php 
        echo $cancel_url;
        ?>
" class="btn btn-danger btn-xs confirm">Cancel Subscription</a></td>
            </tr>
            <?php 
    }
    ?>
    </table>
    <?php 
}
$invoices = \Stripe\Invoice::all(array("limit" => 300, "customer" => $user->stripe_cust));
?>
<h2>Invoices</h2>

<?php 
echo "<table class='table table-striped table-bordered table-hover'>";
echo "<tr>";
echo "<th>Invoice Date</th>";
echo "<th>Invoice Id</th>";
echo "<th>Total</th>";
echo "<th>Status</th>";
echo "<th>Details</th>";
echo "</tr>";
foreach ($invoices['data'] as $invoice) {
    $class = $invoice->paid ? "success" : "warning";
    echo "<tr class='{$class}'>";
 public function invoicesAction(Request $request)
 {
     try {
         $customer_id = $request->query->get('customer_id');
         $limit = $request->query->get('limit') ? $request->query->get('limit') : 10;
         $starting_after = $request->query->get('starting_after') ? $request->query->get('starting_after') : -1;
         $ending_before = $request->query->get('ending_before') ? $request->query->get('ending_before') : -1;
         $date = $request->query->get('date') ? $request->query->get('date') : -1;
         $request_array = array("customer" => $customer_id, "limit" => $limit);
         if ($starting_after != -1) {
             $request_array["starting_after"] = $starting_after;
         }
         if ($ending_before != -1) {
             $request_array["ending_before"] = $ending_before;
         }
         if ($date != -1) {
             $date_params = array("gt" => $date);
             $request_array["date"] = $date_params;
         }
         \Stripe\Stripe::setApiKey("sk_test_DxL4C2nUSAVBILG7FtnY4mYs");
         $response = \Stripe\Invoice::all($request_array);
         $invoices = array();
         $i = 0;
         foreach ($response['data'] as $invoice) {
             $invoice_item = array("date" => $invoice['date'], "end" => $invoice['lines']['data'][0]['period']['end'], "name" => $invoice['lines']['data'][0]['plan']['name'], "id" => $invoice['id'], "interval" => $invoice['lines']['data'][0]['plan']['interval'], "total" => $invoice['total']);
             $invoices[$i] = $invoice_item;
             $i++;
         }
         $invoices = json_encode($invoices);
     } catch (\Stripe\Error\ApiConnection $e) {
         // Network communication with Stripe failed
         $error = array("error" => "Connection Error");
         return new Response(json_encode($error), 422);
     } catch (\Stripe\Error\Authentication $e) {
         // Authentication with Stripe's API failed
         $error = array("error" => "Invalid API Key");
         return new Response(json_encode($error), 422);
     } catch (\Stripe\Error\InvalidRequest $e) {
         // Invalid parameters were supplied to Stripe's API
         $error = array("error" => "Invalid Request", "array" => $request_array);
         return new Response(json_encode($error), 422);
     } catch (\Stripe\Error\Base $e) {
         // Display a very generic error to the user, and maybe send
         $error = array("error" => $e);
         return new Response(json_encode($error), 422);
     } catch (Exception $e) {
         // Something else happened, completely unrelated to Stripe
         $error = array("error" => $e);
         return new Response(json_encode($error), 422);
     }
     return new Response($invoices, 200);
 }
Example #9
0
 /**
  * Find an invoice by ID.
  *
  * @param string $id
  *
  * @return Invoice|null
  */
 public function findInvoice($id)
 {
     try {
         return new Invoice($this, StripeInvoice::retrieve($id, $this->getStripeKey()));
     } catch (Exception $e) {
     }
 }
Example #10
0
 /**
  *
  * @SWG\Api(
  *   path="/billing_history",
  *   description="API for user actions",
  * @SWG\Operation(
  *    method="GET",
  *    type="array[Invoice]",
  *    summary="Retrieve a user's billing history",
  *   )
  * )
  */
 public function billing_history_get()
 {
     $this->validate_user();
     $this->load->model(array('Plan', 'Subscription'));
     $this->load->helper('notification');
     \Stripe\Stripe::setApiKey($this->config->item('stripe_private_key'));
     $subscription = $this->Subscription->load_by_user_id(get_user_id());
     if ($subscription) {
         try {
             $invoices = \Stripe\Invoice::all(array("customer" => $subscription->stripe_customer_id, "limit" => 12));
             //array_print($invoices);
         } catch (Exception $e) {
             log_message('error', 'Exception while retrieving billing history: ' . $e->getMessage());
             json_error('We experienced an error while retrieving your billing history: ' . $e->getMessage());
             return;
         }
         $this->response(decorate_invoices($invoices->data));
     } else {
         $this->response(array());
     }
 }
 /**
  * Process registration
  *
  * @since 2.1
  */
 public function process_signup()
 {
     \Stripe\Stripe::setApiKey($this->secret_key);
     $paid = false;
     $member = new RCP_Member($this->user_id);
     $customer_exists = false;
     if (empty($_POST['stripeToken'])) {
         wp_die(__('Missing Stripe token, please try again or contact support if the issue persists.', 'rcp'), __('Error', 'rcp'), array('response' => 400));
     }
     if ($this->auto_renew) {
         // process a subscription sign up
         $plan_id = strtolower(str_replace(' ', '', $this->subscription_name));
         if (!$this->plan_exists($plan_id)) {
             // create the plan if it doesn't exist
             $this->create_plan($this->subscription_name);
         }
         try {
             $customer_id = $member->get_payment_profile_id();
             if ($customer_id) {
                 $customer_exists = true;
                 try {
                     // Update the customer to ensure their card data is up to date
                     $customer = \Stripe\Customer::retrieve($customer_id);
                     if (isset($customer->deleted) && $customer->deleted) {
                         // This customer was deleted
                         $customer_exists = false;
                     }
                     // No customer found
                 } catch (Exception $e) {
                     $customer_exists = false;
                 }
             }
             // Customer with a discount
             if (!empty($this->discount_code)) {
                 if ($customer_exists) {
                     $customer->card = $_POST['stripeToken'];
                     $customer->coupon = $this->discount_code;
                     $customer->save();
                     // Update the customer's subscription in Stripe
                     $customer_response = $customer->updateSubscription(array('plan' => $plan_id));
                 } else {
                     $customer = \Stripe\Customer::create(apply_filters('rcp_stripe_customer_create_args', array('card' => $_POST['stripeToken'], 'plan' => $plan_id, 'email' => $this->email, 'description' => 'User ID: ' . $this->user_id . ' - User Email: ' . $this->email . ' Subscription: ' . $this->subscription_name, 'coupon' => $_POST['rcp_discount']), $this));
                 }
                 // Customer without a discount
             } else {
                 if ($customer_exists) {
                     $customer->card = $_POST['stripeToken'];
                     $customer->save();
                     // Update the customer's subscription in Stripe
                     $customer_response = $customer->updateSubscription(array('plan' => $plan_id));
                 } else {
                     $customer = \Stripe\Customer::create(apply_filters('rcp_stripe_customer_create_args', array('card' => $_POST['stripeToken'], 'plan' => $plan_id, 'email' => $this->email, 'description' => 'User ID: ' . $this->user_id . ' - User Email: ' . $this->email . ' Subscription: ' . $this->subscription_name), $this));
                 }
             }
             if (!empty($this->signup_fee)) {
                 if ($this->signup_fee > 0) {
                     $description = sprintf(__('Signup Fee for %s', 'rcp_stripe'), $this->subscription_name);
                 } else {
                     $description = sprintf(__('Signup Discount for %s', 'rcp_stripe'), $this->subscription_name);
                 }
                 \Stripe\InvoiceItem::create(apply_filters('rcp_stripe_invoice_item_create_args', array('customer' => $customer->id, 'amount' => $this->signup_fee * 100, 'currency' => strtolower($this->currency), 'description' => $description), $this, $customer));
                 // Create the invoice containing taxes / discounts / fees
                 $invoice = \Stripe\Invoice::create(apply_filters('rcp_stripe_invoice_create_args', array('customer' => $customer->id), $this, $customer));
                 $invoice->pay();
             }
             $member->set_payment_profile_id($customer->id);
             // subscription payments are recorded via webhook
             $paid = true;
         } catch (\Stripe\Error\Card $e) {
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
             exit;
         } catch (\Stripe\Error\InvalidRequest $e) {
             // Invalid parameters were supplied to Stripe's API
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Authentication $e) {
             // Authentication with Stripe's API failed
             // (maybe you changed API keys recently)
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\ApiConnection $e) {
             // Network communication with Stripe failed
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Base $e) {
             // Display a very generic error to the user
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (Exception $e) {
             // Something else happened, completely unrelated to Stripe
             $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
             $error .= print_r($e, true);
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         }
     } else {
         // process a one time payment signup
         try {
             $charge = \Stripe\Charge::create(apply_filters('rcp_stripe_charge_create_args', array('amount' => $this->amount * 100, 'currency' => strtolower($this->currency), 'card' => $_POST['stripeToken'], 'description' => 'User ID: ' . $this->user_id . ' - User Email: ' . $this->email . ' Subscription: ' . $this->subscription_name, 'receipt_email' => $this->email, 'metadata' => array('email' => $this->email, 'user_id' => $this->user_id, 'level_id' => $this->subscription_id, 'level' => $this->subscription_name, 'key' => $this->subscription_key)), $this));
             $payment_data = array('date' => date('Y-m-d g:i:s', time()), 'subscription' => $this->subscription_name, 'payment_type' => 'Credit Card One Time', 'subscription_key' => $this->subscription_key, 'amount' => $this->amount, 'user_id' => $this->user_id, 'transaction_id' => $charge->id);
             $rcp_payments = new RCP_Payments();
             $rcp_payments->insert($payment_data);
             $paid = true;
         } catch (\Stripe\Error\Card $e) {
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
             exit;
         } catch (\Stripe\Error\InvalidRequest $e) {
             // Invalid parameters were supplied to Stripe's API
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Authentication $e) {
             // Authentication with Stripe's API failed
             // (maybe you changed API keys recently)
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\ApiConnection $e) {
             // Network communication with Stripe failed
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (\Stripe\Error\Base $e) {
             // Display a very generic error to the user
             $body = $e->getJsonBody();
             $err = $body['error'];
             $error = '<h4>' . __('An error occurred', 'rcp') . '</h4>';
             if (isset($err['code'])) {
                 $error .= '<p>' . sprintf(__('Error code: %s', 'rcp'), $err['code']) . '</p>';
             }
             $error .= "<p>Status: " . $e->getHttpStatus() . "</p>";
             $error .= "<p>Message: " . $err['message'] . "</p>";
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         } catch (Exception $e) {
             // Something else happened, completely unrelated to Stripe
             $error = '<p>' . __('An unidentified error occurred.', 'rcp') . '</p>';
             $error .= print_r($e, true);
             wp_die($error, __('Error', 'rcp'), array('response' => '401'));
         }
     }
     if ($paid) {
         // set this user to active
         $member->renew($this->auto_renew);
         if (!is_user_logged_in()) {
             // log the new user in
             rcp_login_user_in($this->user_id, $this->user_name, $_POST['rcp_user_pass']);
         }
         do_action('rcp_stripe_signup', $this->user_id, $this);
     } else {
         wp_die(__('An error occurred, please contact the site administrator: ', 'rcp_stripe') . get_bloginfo('admin_email'), __('Error', 'rcp'), array('response' => '401'));
     }
     // redirect to the success page, or error page if something went wrong
     wp_redirect($this->return_url);
     exit;
 }
Example #12
0
 public function getInvoices($customerId)
 {
     $invoices = Invoice::all(array('customer' => $customerId))->data;
     return array_map(function ($invoice) {
         return new Invoice($invoice->date, $invoice->total, $invoice->paid);
     }, $invoices);
 }
Example #13
0
<?php

require_once '../config.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $postdata = @file_get_contents("php://input");
    $event = json_decode($postdata);
    if ($event->type == 'invoice.payment_succeeded') {
        $customer_id = $event->data->object->customer;
        $customer = \Stripe\Customer::retrieve($customer_id);
        $invoice = \Stripe\Invoice::retrieve($event->data->object->id);
        // This is where we'd normally e-mail the invoice, but we'll just write out the invoice to a file instead.
        $from = "From: Oscar Wilde";
        $to = "To: " . $customer->email;
        $subject = "Subject: You have made a payment for another month of Wilde quotes";
        $body = "You have made a new payment for \$" . $invoice->total / 100.0 . ":\n\n";
        foreach ($invoice->lines->data as &$line) {
            if ($line->type == 'subscription') {
                $body .= "Subscription - " . $line->plan->name . ": " . $line->amount . "\n";
            } else {
                if ($line->type == 'invoiceitem') {
                    $body .= "Additional -" . $line->description . ": " . $line->amount;
                }
            }
        }
        $email_file = fopen($customer->id . "-" . $invoice->date, 'a');
        $email = $from . "\n" . $to . "\n" . $subject . "\n" . $body;
        fwrite($email_file, $email);
    }
}
Example #14
0
 /**
  * Retrieve stripe invoice object
  *
  * @param string $id Invoice StripeID
  *
  * @return \Stripe\Invoice
  */
 public function retrieve($id)
 {
     return StripeInvoiceApi::retrieve($id);
 }
 *
 * @author     Shane Barron <*****@*****.**>
 * @author     Aaustin Barron <*****@*****.**>
 * @copyright  2015 SocialApparatus
 * @license    http://opensource.org/licenses/MIT MIT
 * @version    1
 * @link       http://socialapparatus.com
 */
namespace SocialApparatus;

denyDirect();
$invoice_number = pageArray(1);
$has_plan = false;
$table = NULL;
\Stripe\Stripe::setApiKey(EcommercePlugin::secretKey());
$lines = \Stripe\Invoice::retrieve($invoice_number)->lines->all(array('limit' => 5000));
echo "<h2 class='text-center'>";
echo "Invoice " . $invoice_number;
echo "</h2>";
foreach ($lines['data'] as $line) {
    $table .= "<tr>";
    $table .= "<td>";
    $table .= $line->id;
    $table .= "</td>";
    $table .= "<td>";
    if ($line->plan) {
        $has_plan = true;
        $plan = $line->plan;
        $plan_id = $plan->id;
        $plan_entity = getEntity($plan_id);
        $table .= $plan_entity->title;
Example #16
0
 /**
  * Get the entity's upcoming invoice.
  *
  * @return \Laravel\Cashier\Invoice|null
  */
 public function upcomingInvoice()
 {
     try {
         $customer = $this->getStripeCustomer();
         $stripeInvoice = StripeInvoice::upcoming(['customer' => $customer->id]);
         return new Invoice($this->billable, $stripeInvoice);
     } catch (StripeErrorInvalidRequest $e) {
         return null;
     }
 }
 * @author     Shane Barron <*****@*****.**>
 * @author     Aaustin Barron <*****@*****.**>
 * @copyright  2015 SocialApparatus
 * @license    http://opensource.org/licenses/MIT MIT
 * @version    1
 * @link       http://socialapparatus.com
 */
namespace SocialApparatus;

denyDirect();
gateKeeper();
$user = getLoggedInUser();
$stripe_cust = $user->stripe_cust;
if ($stripe_cust) {
    \Stripe\Stripe::setApiKey(EcommercePlugin::secretKey());
    $invoices = \Stripe\Invoice::all(array("customer" => $stripe_cust));
    echo "<table class='table table-striped table-bordered table-hover'>";
    echo "<tr>";
    echo "<th>Invoice Date</th>";
    echo "<th>Invoice Id</th>";
    echo "<th>Total</th>";
    echo "<th>Status</th>";
    echo "<th>Details</th>";
    echo "</tr>";
    foreach ($invoices['data'] as $invoice) {
        $class = $invoice->paid ? "success" : "warning";
        echo "<tr class='{$class}'>";
        echo "<td>";
        echo date("m/d/Y", $invoice->date);
        echo "</td>";
        echo "<td>";
Example #18
0
 public function get_invoice_test($stripe_customer_id)
 {
     try {
         \Stripe\Stripe::setApiKey($this->config->item("stripe_secret_key"));
         $reply = \Stripe\Invoice::all(array("customer" => $stripe_customer_id));
         $data = $reply->data;
         $response = $data;
         $total_invoices = count($response);
         for ($r = 0; $r < $total_invoices; $r++) {
             $stripe_invoice_id = $response[$r]->id;
             $invoice_amount = $response[$r]->amount_due;
             $invoice_date = $response[$r]->date;
             //$closed = $response[$r]->closed;
             $lines = $response[$r]->lines;
             $data = $lines->data;
             $next_payment_attempt = $response[$r]->next_payment_attempt;
             $paid = $response[$r]->paid;
             $receipt_number = $lines->receipt_number;
             echo "<br/>Invoice Amount = " . $invoice_amount;
             $total_invoice_items = count($data);
             for ($s = 0; $s < $total_invoice_items; $s++) {
                 $subscription_id = $data[$s]->id;
                 $amount = $data[$s]->amount;
                 $quantity = $data[$s]->quantity;
                 echo "<br/>Invoice Item Amount = " . $amount;
             }
         }
         $return['message'] = 'true';
         $return['response'] = 'Invoice added successfully';
     } catch (\Stripe\Error\Card $e) {
         // Since it's a decline, \Stripe\Error\Card will be caught
         $body = $e->getJsonBody();
         $err = $body['error'];
         $return['message'] = 'false';
         $return['response'] = $err['message'];
         /*echo('Status is:' . $e->getHttpStatus() . "\n");
         		echo('Type is:' . $err['type'] . "\n");
         		echo('Code is:' . $err['code'] . "\n");
         		// param is '' in this case
         		echo('Param is:' . $err['param'] . "\n");
         		echo('Message is:' . $err['message'] . "\n");*/
     } catch (\Stripe\Error\RateLimit $e) {
         // Too many requests made to the API too quickly
         $return['message'] = 'false';
         $return['response'] = $e->getMessage();
     } catch (\Stripe\Error\InvalidRequest $e) {
         // Invalid parameters were supplied to Stripe's API
         $return['message'] = 'false';
         $return['response'] = $e->getMessage();
     } catch (\Stripe\Error\Authentication $e) {
         // Authentication with Stripe's API failed
         // (maybe you changed API keys recently)
         $return['message'] = 'false';
         $return['response'] = $e->getMessage();
     } catch (\Stripe\Error\ApiConnection $e) {
         // Network communication with Stripe failed
         $return['message'] = 'false';
         $return['response'] = $e->getMessage();
     } catch (\Stripe\Error\Base $e) {
         // Display a very generic error to the user, and maybe send
         $return['message'] = 'false';
         $return['response'] = $e->getMessage();
         // yourself an email
     } catch (Exception $e) {
         // Something else happened, completely unrelated to Stripe
         $return['message'] = 'false';
         $return['response'] = $e->getMessage();
     }
     return $return;
 }