/**
  * Verify with Stripe that the event is genuine.
  *
  * @param  string $id
  * @return bool
  */
 protected function eventExistsOnStripe($id)
 {
     try {
         return !is_null(StripeEvent::retrieve($id, env('STRIPE_SECRET')));
     } catch (Exception $e) {
         return false;
     }
 }
 /**
  * Verify with Stripe that the event is genuine.
  *
  * @param  string  $id
  * @return bool
  */
 protected function eventExistsOnStripe($id)
 {
     try {
         return !is_null(StripeEvent::retrieve($id, config('services.stripe.secret')));
     } catch (Exception $e) {
         return false;
     }
 }
Example #3
0
/**
 * Gerer les webhooks Stripe
 *
 * @param array $config
 * @param null|array $response
 * @return array
 */
function presta_stripe_call_autoresponse_dist($config)
{
    include_spip('inc/bank');
    $mode = $config['presta'];
    if (isset($config['mode_test']) and $config['mode_test']) {
        $mode .= "_test";
    }
    // charger l'API Stripe avec la cle
    stripe_init_api($config);
    // Retrieve the request's body and parse it as JSON
    $input = @file_get_contents("php://input");
    $event_json = json_decode($input);
    $event_id = $event_json->id;
    $event = false;
    $erreur = $erreur_code = '';
    $res = false;
    try {
        // $event_id = 'evt_194CExB63f1NFl4k4qNLVNiS'; // debug
        // Verify the event by fetching it from Stripe
        $event = \Stripe\Event::retrieve($event_id);
    } catch (Exception $e) {
        if ($body = $e->getJsonBody()) {
            $err = $body['error'];
            list($erreur_code, $erreur) = stripe_error_code($err);
        } else {
            $erreur = $e->getMessage();
            $erreur_code = 'error';
        }
    }
    $inactif = "";
    if (!$config['actif']) {
        $inactif = "(inactif) ";
    }
    if ($erreur or $erreur_code) {
        spip_log('call_autoresponse ' . $inactif . ': ' . "{$erreur_code} - {$erreur}", $mode . 'auto' . _LOG_ERREUR);
    } else {
        if ($event) {
            $type = $event->type;
            $type = preg_replace(',\\W,', '_', $type);
            if (function_exists($f = "stripe_webhook_{$type}") or function_exists($f = $f . '_dist')) {
                spip_log("call_autoresponse : event {$type} => {$f}()", $mode . 'auto' . _LOG_DEBUG);
                $res = $f($config, $event);
            } else {
                spip_log("call_autoresponse : event {$type} - {$f} not existing", $mode . 'auto' . _LOG_DEBUG);
            }
        }
    }
    include_spip('inc/headers');
    http_status(200);
    // No Content
    header("Connection: close");
    if ($res) {
        return $res;
    }
    exit;
}
Example #4
0
 /**
  * This function tells the controller to process the Stripe event.
  *
  * @return string output
  */
 public function handle(array $event)
 {
     if (!isset($event['id'])) {
         return self::ERROR_INVALID_EVENT;
     }
     // check that the livemode matches our development state
     $environment = $this->app['environment'];
     if (!($event['livemode'] && $environment === Application::ENV_PRODUCTION || !$event['livemode'] && $environment !== Application::ENV_PRODUCTION)) {
         return self::ERROR_LIVEMODE_MISMATCH;
     }
     if (isset($event['user_id'])) {
         return self::ERROR_STRIPE_CONNECT_EVENT;
     }
     // grab up the API key
     $this->apiKey = $this->app['config']->get('stripe.secret');
     try {
         // retreive the event, unless it is a deauth event
         // since those cannot be retrieved
         $validatedEvent = $event['type'] == 'account.application.deauthorized' ? (object) $event : Event::retrieve($event['id'], $this->apiKey);
         // get the data attached to the event
         $eventData = $validatedEvent->data->object;
         // find out which user this event is for by cross-referencing the customer id
         $modelClass = $this->app['config']->get('billing.model');
         $member = $modelClass::where('stripe_customer', $eventData->customer)->first();
         if (!$member) {
             return self::ERROR_CUSTOMER_NOT_FOUND;
         }
         // determine handler by checking if the method exists
         // i.e customer.subscription.created -> handleCustomerSubscriptionCreated
         $inflector = Inflector::get();
         $method = str_replace('.', '_', $validatedEvent->type);
         $method = 'handle' . $inflector->camelize($method);
         if (!method_exists($this, $method)) {
             return self::ERROR_EVENT_NOT_SUPPORTED;
         }
         if ($this->{$method}($eventData, $member)) {
             return self::SUCCESS;
         }
     } catch (StripeError $e) {
         $this->app['logger']->error($e);
     }
     return self::ERROR_GENERIC;
 }
<?php

$parse_uri = explode('wp-content', $_SERVER['SCRIPT_FILENAME']);
$wp_load = $parse_uri[0] . 'wp-load.php';
// Total WP Load Code.
require_once $wp_load;
require_once plugin_dir_path(__FILE__) . 'vendor/autoload.php';
\Stripe\Stripe::setApiKey("sk_test_lC6IlLsQ7Mp7CIS1QR6yM4Nn");
// Retrieve the request's body and parse it as JSON
$input = @file_get_contents("php://input");
$event_json = json_decode($input);
$event_id = $event_json->id;
$event = \Stripe\Event::retrieve($event_id);
$event_object = $event->data->object;
if ($event->type == 'charge.succeeded') {
    $event_object = $event->data->object;
    $amount = sprintf('%0.2f', $event_object->amount / 100.0);
    // amount
    $balance_transaction = $event_object->balance_transaction;
    $carged_id = $event_object->id;
    $event_metadata = $event_object->metadata;
    if (isset($event_metadata->item_number)) {
        $order_page = array('post_title' => $event_metadata->item_name, 'post_content' => '', 'post_status' => 'publish', 'post_author' => 1, 'post_type' => 'investment');
        $post_id = wp_insert_post($order_page);
        add_post_meta($post_id, 'themeum_project_name', esc_attr($event_metadata->item_name));
        add_post_meta($post_id, 'themeum_invest_id', esc_attr($carged_id));
        add_post_meta($post_id, 'themeum_investor_user_id', esc_attr($event_metadata->user_id));
        add_post_meta($post_id, 'themeum_investment_project_id', esc_attr($event_metadata->item_number));
        add_post_meta($post_id, 'themeum_investment_amount', esc_attr($amount));
        add_post_meta($post_id, 'themeum_payment_id', esc_attr($balance_transaction));
        add_post_meta($post_id, 'themeum_payment_method', 'stripe');
 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');
 }
Example #7
0
 /**
  * Getting specific events for the user (null = all)
  * @param user object
  * 
  * @return an array with the events
  */
 public static function getEvents($user)
 {
     $out_events = array();
     // initializing variables
     $has_more = true;
     $foundLatestEvent = false;
     $latestEvent = Abf\Event::where('user', $user->id)->where('provider', 'stripe')->orderBy('created', 'desc')->first();
     $last_obj = null;
     // continue request as long as there is more AND we don't already have it
     while ($has_more && !$foundLatestEvent) {
         // trying to avoid overflow
         $previous_last_obj = $last_obj;
         // telling stripe who we are
         if (strlen($user->stripe_key) > 2) {
             Stripe::setApiKey($user->stripe_key);
             if ($last_obj) {
                 // we have last obj -> starting from there
                 $returned_object = Event::all(array('limit' => 20, 'starting_after' => $last_obj));
             } else {
                 // starting from zero
                 $returned_object = Event::all(array('limit' => 100));
             }
         } else {
             Stripe::setApiKey($_ENV['STRIPE_SECRET_KEY']);
             if ($last_obj) {
                 // we have last obj -> starting from there
                 $returned_object = Event::all(array('limit' => 20, 'starting_after' => $last_obj), array('stripe_account' => $user->stripeUserId));
             } else {
                 // starting from zero
                 $returned_object = Event::all(array('limit' => 100), array('stripe_account' => $user->stripeUserId));
             }
         }
         // getting the events
         // https://stripe.com/docs/api/php#events
         // pagination....
         // extractin json (this is not the best approach)
         $events = json_decode(strstr($returned_object, '{'), true);
         // getting relevant fields
         foreach ($events['data'] as $event) {
             // updating array
             /*
             created     - timestamp
             type        - string, see https://stripe.com/docs/api/php#event_types
             object      - hash map (assoc array)
             */
             if (isset($event['data']['object'])) {
                 if ($latestEvent) {
                     if ($event['id'] == $latestEvent->eventID) {
                         $foundLatestEvent = true;
                     }
                 }
                 $out_events[$event['id']] = array('created' => $event['created'], 'type' => $event['type'], 'data' => $event['data'], 'provider' => 'stripe');
                 $last_obj = $event['id'];
             }
         }
         // foreach
         // updating has_more
         $has_more = $events['has_more'];
         // avoiding infinite loop
         if ($previous_last_obj == $last_obj and $has_more) {
             // we should never get here
             // this is too bad system failure :(
             $has_more = false;
         }
     }
     // while
     // returning object
     return $out_events;
 }
 /**
  * request method
  *
  * @param string $method
  * @param array $data
  *
  * @return array - containing 'status', 'message' and 'data' keys
  * 					if response was successful, keys will be 'success', 'Success' and the stripe response as associated array respectively,
  *   				if request failed, keys will be 'error', the card error message if it was card_error, boolen false otherwise, and
  *   								error data as an array respectively
  */
 private function request($method = null, $data = null)
 {
     if (!$method) {
         throw new Exception(__('Request method is missing'));
     }
     if (is_null($data)) {
         throw new Exception(__('Request Data is not provided'));
     }
     Stripe::setApiKey($this->key);
     $success = null;
     $error = null;
     $message = false;
     $log = null;
     try {
         switch ($method) {
             /**
              *
              * 		CHARGES
              *
              */
             case 'charge':
                 $success = $this->fetch(Charge::create($data));
                 break;
             case 'retrieveCharge':
                 $success = $this->fetch(Charge::retrieve($data['charge_id']));
                 if (!empty($success['refunds'])) {
                     foreach ($success['refunds'] as &$refund) {
                         $refund = $this->fetch($refund);
                     }
                 }
                 break;
             case 'updateCharge':
                 $charge = Charge::retrieve($data['charge_id']);
                 foreach ($data['fields'] as $field => $value) {
                     $charge->{$field} = $value;
                 }
                 $success = $this->fetch($charge->save());
                 break;
             case 'refundCharge':
                 $charge = Charge::retrieve($data['charge_id']);
                 // to prevent unknown param error
                 unset($data['charge_id']);
                 $success = $this->fetch($charge->refund($data));
                 foreach ($success['refunds']['data'] as &$refund) {
                     $refund = $this->fetch($refund);
                 }
                 break;
             case 'captureCharge':
                 $charge = Charge::retrieve($data['charge_id']);
                 unset($data['charge_id']);
                 $success = $this->fetch($charge->capture($data));
                 if (!empty($success['refunds']['data'])) {
                     foreach ($success['refunds']['data'] as &$refund) {
                         $refund = $this->fetch($refund);
                     }
                 }
                 break;
             case 'listCharges':
                 $charges = Charge::all();
                 $success = $this->fetch($charges);
                 foreach ($success['data'] as &$charge) {
                     $charge = $this->fetch($charge);
                     if (isset($charge['refunds']['data']) && !empty($charge['refunds']['data'])) {
                         foreach ($charge['refunds']['data'] as &$refund) {
                             $refund = $this->fetch($refund);
                         }
                         unset($refund);
                     }
                 }
                 break;
                 /**
                  * 		CUSTOMERS
                  */
             /**
              * 		CUSTOMERS
              */
             case 'createCustomer':
                 $customer = Customer::create($data);
                 $success = $this->fetch($customer);
                 if (!empty($success['cards']['data'])) {
                     foreach ($success['cards']['data'] as &$card) {
                         $card = $this->fetch($card);
                     }
                     unset($card);
                 }
                 if (!empty($success['subscriptions']['data'])) {
                     foreach ($success['subscriptions']['data'] as &$subscription) {
                         $subscription = $this->fetch($subscription);
                     }
                     unset($subscription);
                 }
                 break;
             case 'retrieveCustomer':
                 $customer = Customer::retrieve($data['customer_id']);
                 $success = $this->fetch($customer);
                 if (!empty($success['cards']['data'])) {
                     foreach ($success['cards']['data'] as &$card) {
                         $card = $this->fetch($card);
                     }
                     unset($card);
                 }
                 if (!empty($success['subscriptions']['data'])) {
                     foreach ($success['subscriptions']['data'] as &$subscription) {
                         $subscription = $this->fetch($subscription);
                     }
                     unset($subscription);
                 }
                 break;
             case 'updateCustomer':
                 $cu = Customer::retrieve($data['customer_id']);
                 foreach ($data['fields'] as $field => $value) {
                     $cu->{$field} = $value;
                 }
                 $success = $this->fetch($cu->save());
                 if (!empty($success['cards']['data'])) {
                     foreach ($success['cards']['data'] as &$card) {
                         $card = $this->fetch($card);
                     }
                     unset($card);
                 }
                 if (!empty($success['subscriptions']['data'])) {
                     foreach ($success['subscriptions']['data'] as &$subscription) {
                         $subscription = $this->fetch($subscription);
                     }
                     unset($subscription);
                 }
                 break;
             case 'deleteCustomer':
                 $cu = Customer::retrieve($data['customer_id']);
                 $success = $this->fetch($cu->delete());
                 break;
             case 'listCustomers':
                 $customers = Customer::all($data['options']);
                 $success = $this->fetch($customers);
                 foreach ($success['data'] as &$customer) {
                     $customer = $this->fetch($customer);
                     if (!empty($customer['cards']['data'])) {
                         foreach ($customer['cards']['data'] as &$card) {
                             $card = $this->fetch($card);
                         }
                         unset($card);
                     }
                     if (!empty($customer['subscriptions']['data'])) {
                         foreach ($customer['subscriptions']['data'] as &$subscription) {
                             $subscription = $this->fetch($subscription);
                         }
                         unset($subscription);
                     }
                 }
                 break;
                 /**
                  * 		CARDS
                  *
                  */
             /**
              * 		CARDS
              *
              */
             case 'createCard':
                 $cu = Customer::retrieve($data['customer_id']);
                 $validCardFields = ['object', 'address_zip', 'address_city', 'address_state', 'address_country', 'address_line1', 'address_line2', 'number', 'exp_month', 'exp_year', 'cvc', 'name', 'metadata'];
                 // unset not valid keys to prevent unknown parameter stripe error
                 unset($data['customer_id']);
                 foreach ($data['source'] as $k => $v) {
                     if (!in_array($k, $validCardFields)) {
                         unset($data['source'][$k]);
                     }
                 }
                 $card = $cu->sources->create($data);
                 $success = $this->fetch($card);
                 break;
             case 'retrieveCard':
                 $cu = Customer::retrieve($data['customer_id']);
                 $card = $cu->sources->retrieve($data['card_id']);
                 $success = $this->fetch($card);
                 break;
             case 'updateCard':
                 $cu = Customer::retrieve($data['customer_id']);
                 $cuCard = $cu->sources->retrieve($data['card_id']);
                 foreach ($data['fields'] as $field => $value) {
                     $cuCard->{$field} = $value;
                 }
                 $card = $cuCard->save();
                 $success = $this->fetch($card);
                 break;
             case 'deleteCard':
                 $cu = Customer::retrieve($data['customer_id']);
                 $card = $cu->sources->retrieve($data['card_id'])->delete();
                 $success = $this->fetch($card);
                 break;
             case 'listCards':
                 $cu = Customer::retrieve($data['customer_id']);
                 $cards = $cu->sources->all($data['options']);
                 $success = $this->fetch($cards);
                 foreach ($success['data'] as &$card) {
                     $card = $this->fetch($card);
                 }
                 break;
                 /**
                  * 		SUBSCRIPTIONS
                  *
                  */
             /**
              * 		SUBSCRIPTIONS
              *
              */
             case 'createSubscription':
                 $cu = Customer::retrieve($data['customer_id']);
                 // unset customer_id to prevent unknown parameter stripe error
                 unset($data['customer_id']);
                 $subscription = $cu->subscriptions->create($data['subscription']);
                 $success = $this->fetch($subscription);
                 break;
             case 'retrieveSubscription':
                 $cu = Customer::retrieve($data['customer_id']);
                 $subscription = $cu->subscriptions->retrieve($data['subscription_id']);
                 $success = $this->fetch($subscription);
                 break;
             case 'updateSubscription':
                 $cu = Customer::retrieve($data['customer_id']);
                 $cuSubscription = $cu->subscriptions->retrieve($data['subscription_id']);
                 foreach ($data['fields'] as $field => $value) {
                     $cuSubscription->{$field} = $value;
                 }
                 $subscription = $cuSubscription->save();
                 $success = $this->fetch($subscription);
                 break;
             case 'cancelSubscription':
                 $cu = Customer::retrieve($data['customer_id']);
                 $subscription = $cu->subscriptions->retrieve($data['subscription_id'])->cancel($data['at_period_end']);
                 $success = $this->fetch($subscription);
                 break;
             case 'listSubscriptions':
                 $cu = Customer::retrieve($data['customer_id']);
                 $subscriptions = $cu->subscriptions->all($data['options']);
                 $success = $this->fetch($subscriptions);
                 foreach ($success['data'] as &$subscription) {
                     $subscription = $this->fetch($subscription);
                 }
                 break;
                 /**
                  * 		PLANS
                  *
                  */
             /**
              * 		PLANS
              *
              */
             case 'createPlan':
                 $plan = Plan::create($data);
                 $success = $this->fetch($plan);
                 break;
             case 'retrievePlan':
                 $plan = Plan::retrieve($data['plan_id']);
                 $success = $this->fetch($plan);
                 break;
             case 'updatePlan':
                 $p = Plan::retrieve($data['plan_id']);
                 foreach ($data['fields'] as $field => $value) {
                     $p->{$field} = $value;
                 }
                 $plan = $p->save();
                 $success = $this->fetch($plan);
                 break;
             case 'deletePlan':
                 $p = Plan::retrieve($data['plan_id']);
                 $plan = $p->delete();
                 $success = $this->fetch($plan);
                 break;
             case 'listPlans':
                 $plans = Plan::all($data['options']);
                 $success = $this->fetch($plans);
                 foreach ($success['data'] as &$plan) {
                     $plan = $this->fetch($plan);
                 }
                 break;
                 /**
                  * 	 	COUPONS
                  *
                  */
             /**
              * 	 	COUPONS
              *
              */
             case 'createCoupon':
                 $coupon = Coupon::create($data);
                 $success = $this->fetch($coupon);
                 break;
             case 'retrieveCoupon':
                 $coupon = Coupon::retrieve($data['coupon_id']);
                 $success = $this->fetch($coupon);
                 break;
             case 'deleteCoupon':
                 $c = Coupon::retrieve($data['coupon_id']);
                 $coupon = $c->delete();
                 $success = $this->fetch($coupon);
                 break;
             case 'listCoupons':
                 $coupons = Coupon::all($data['options']);
                 $success = $this->fetch($coupons);
                 foreach ($success['data'] as &$coupon) {
                     $coupon = $this->fetch($coupon);
                 }
                 break;
                 /**
                  *
                  *  	EVENTS
                  *
                  */
             /**
              *
              *  	EVENTS
              *
              */
             case 'retrieveEvent':
                 $event = Event::retrieve($data['event_id']);
                 $success = $this->fetch($event);
                 // cards
                 if (isset($success['data']['object']['cards']['data']) && !empty($success['data']['object']['cards']['data'])) {
                     foreach ($success['data']['object']['cards']['data'] as &$card) {
                         $card = $this->fetch($card);
                     }
                     unset($refund);
                 }
                 break;
             case 'listEvents':
                 $events = Event::all($data['options']);
                 $success = $this->fetch($events);
                 foreach ($success['data'] as &$event) {
                     $event = $this->fetch($event);
                     // refunds
                     if (isset($event['data']['object']['refunds']) && !empty($event['data']['object']['refunds'])) {
                         foreach ($event['data']['object']['refunds'] as &$refund) {
                             $refund = $this->fetch($refund);
                         }
                         unset($refund);
                     }
                     // cards
                     if (isset($event['data']['object']['cards']['data']) && !empty($event['data']['object']['cards']['data'])) {
                         foreach ($event['data']['object']['cards']['data'] as &$card) {
                             $card = $this->fetch($card);
                         }
                         unset($refund);
                     }
                 }
                 break;
         }
     } catch (Card $e) {
         $body = $e->getJsonBody();
         $error = $body['error'];
         $error['http_status'] = $e->getHttpStatus();
         $message = $error['message'];
     } catch (InvalidRequest $e) {
         $body = $e->getJsonBody();
         $error = $body['error'];
         $error['http_status'] = $e->getHttpStatus();
     } catch (Authentication $e) {
         $error = $e->getJsonBody();
         $error['http_status'] = $e->getHttpStatus();
     } catch (ApiConnection $e) {
         $body = $e->getJsonBody();
         $error['http_status'] = $e->getHttpStatus();
     } catch (Base $e) {
         $body = $e->getJsonBody();
         $error['http_status'] = $e->getHttpStatus();
     } catch (\Exception $e) {
         $body = $e->getJsonBody();
         $error['http_status'] = $e->getHttpStatus();
     }
     if ($success) {
         //             if ($this->logFile && in_array($this->logType, ['both', 'success'])) {
         //                 CakeLog::write('Success', $method, $this->logFile);
         //             }
         return ['status' => 'success', 'message' => 'Success', 'response' => $success];
     }
     $str = '';
     $str .= $method . ", type:" . (!empty($error['type']) ? $error['type'] : '');
     $str .= ", type:" . (!empty($error['type']) ? $error['type'] : '');
     $str .= ", http_status:" . (!empty($error['http_status']) ? $error['http_status'] : '');
     $str .= ", param:" . (!empty($error['param']) ? $error['param'] : '');
     $str .= ", message:" . (!empty($error['message']) ? $error['message'] : '');
     //         if ($this->logFile && in_array($this->logType, array('both', 'error'))) {
     //             CakeLog::write('Error', $str, $this->logFile );
     //         }
     return ['status' => 'error', 'message' => $message, 'response' => $error];
 }
 /**
  * getEvents
  * Getting events from the last 30 days.
  * --------------------------------------------------
  * @returns The stripe events.
  * @throws StripeNotConnected
  * --------------------------------------------------
  */
 public function getEvents()
 {
     /* Connecting to stripe, and making query. */
     $rawData = array();
     $decodedData = array();
     $hasMore = TRUE;
     $startingAfter = null;
     while ($hasMore) {
         try {
             /* Collecting events with pagination. */
             if ($startingAfter) {
                 $rawData = \Stripe\Event::all(array("limit" => 100, "starting_after" => $startingAfter));
             } else {
                 $rawData = \Stripe\Event::all(array("limit" => 100));
             }
             /* Adding objects to collection. */
             $currentData = json_decode($this->loadJSON($rawData), TRUE);
             $decodedData = array_merge($decodedData, $currentData['data']);
         } catch (\Stripe\Error\Authentication $e) {
             // Access token expired. Calling handler.
             $this->getNewAccessToken();
         }
         $hasMore = $currentData['has_more'];
         $startingAfter = end($currentData['data'])['id'];
     }
     // Getting the plans.
     $events = [];
     foreach ($decodedData as $event) {
         array_push($events, $event);
     }
     // Return.
     return $events;
 }
 /**
  * Verify with Stripe that the event is genuine.
  *
  * @param string $id
  *
  * @return bool
  */
 protected function eventExistsOnStripe($id)
 {
     try {
         return !is_null(StripeEvent::retrieve($id, Yii::$app->params['stripe']['apiKey']));
     } catch (Exception $e) {
         return false;
     }
 }
 public function process_webhooks()
 {
     if (!isset($_GET['listener']) || strtolower($_GET['listener']) != 'stripe') {
         return;
     }
     // Ensure listener URL is not cached by W3TC
     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);
     // 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);
             $invoice = $event->data->object;
             if (empty($invoice->customer)) {
                 die('no customer attached');
             }
             // retrieve the customer who made this payment (only for subscriptions)
             $user = rcp_get_member_id_from_profile_id($invoice->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", $invoice->customer));
             }
             if (empty($user)) {
                 die('no user ID found');
             }
             $member = new RCP_Member($user);
             // check to confirm this is a stripe subscriber
             if ($member) {
                 // successful payment
                 if ($event->type == 'charge.succeeded') {
                     if (!$member->get_subscription_id()) {
                         die('no subscription ID for member');
                     }
                     $payment_data = array('date' => date('Y-m-d g:i:s', $event->created), 'subscription' => $member->get_subscription_name(), 'payment_type' => 'Credit Card', 'subscription_key' => $member->get_subscription_key(), 'amount' => $invoice->amount / 100, 'user_id' => $member->ID, 'transaction_id' => $invoice->id);
                     if (!rcp_check_for_existing_payment($payment_data['payment_type'], $payment_data['date'], $payment_data['subscription_key'])) {
                         // record this payment if it hasn't been recorded yet
                         $rcp_payments->insert($payment_data);
                         $member->renew($member->is_recurring());
                         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') {
                     $member->set_status('cancelled');
                     die('member cancelled successfully');
                 }
                 do_action('rcp_stripe_' . $event->type, $invoice);
             }
         } catch (Exception $e) {
             // something failed
             die('PHP exception: ' . $e->getMessage());
         }
         die('1');
     }
     die('no event ID found');
 }
 /**
  * Retrieve the specified Stripe Event.
  *
  * @param string $event_id Stripe Event ID.
  *
  * @return mixed
  */
 public function get_stripe_event($event_id)
 {
     // Include Stripe API library.
     $this->include_stripe_api();
     // Get Stripe event.
     $event = \Stripe\Event::retrieve($event_id);
     return $event;
 }
Example #13
0
 /**
  * Retrieve event object
  *
  * @param string $id
  *
  * @return \Stripe\Event
  */
 public function retrieve($id)
 {
     return StripeEventApi::retrieve($id);
 }