Inheritance: extends stripe\ApiResource
 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;
     }
 }
Exemplo n.º 2
1
 public function charge()
 {
     $id = $this->inputfilter->clean($this->app->get('PARAMS.id'), 'alnum');
     $subscription = $this->getModel()->setState('filter.id', $id)->getItem();
     // Get the credit card token submitted by the form
     $token = $this->inputfilter->clean($this->app->get('POST.stripeToken'), 'string');
     $email = $this->inputfilter->clean($this->app->get('POST.stripeEmail'), 'string');
     // Create the charge on Stripe's servers - this will charge the user's card
     try {
         //create a stripe user
         $user = \Stripe\Customer::create(array("description" => "Customer for " . $email, "email" => $email, "card" => $token));
         $user->subscriptions->create(array("plan" => $subscription->plan));
         // this needs to be created empty in model
         $subscription->set('subscriber.id', $user->id);
         $subscription->set('subscriber.email', $user->email);
         $subscription->set('client.email', $email);
         $subscription->save();
         // SEND email to the client
         $this->app->set('subscription', $subscription);
         $this->app->set('plan', \Stripe\Plan::retrieve($subscription->{'plan'}));
         // $subscription->sendChargeEmailClient($subscription);
         //$subscription->sendChargeEmailAdmin($subscription);
         $view = \Dsc\System::instance()->get('theme');
         echo $view->render('Striper/Site/Views::subscription/success.php');
     } catch (\Stripe\CardError $e) {
         //set error message
         // The card has been declined
         $view = \Dsc\System::instance()->get('theme');
         echo $view->render('Striper/Site/Views::subscription/index.php');
     }
 }
Exemplo n.º 3
1
/**
 * Gerer la reponse du POST JS sur paiement/abonnement
 * @param array $config
 * @param array $response
 * @return array
 */
function stripe_traite_reponse_transaction($config, &$response)
{
    $mode = $config['presta'];
    if (isset($config['mode_test']) and $config['mode_test']) {
        $mode .= "_test";
    }
    $config_id = bank_config_id($config);
    $is_abo = (isset($response['abo']) and $response['abo']);
    if (!isset($response['id_transaction']) or !isset($response['transaction_hash'])) {
        return bank_transaction_invalide(0, array('mode' => $mode, 'erreur' => "transaction inconnue", 'log' => var_export($response, true)));
    }
    if ((!isset($response['charge_id']) or !$response['charge_id']) and (!isset($response['token']) or !$response['token'])) {
        return bank_transaction_invalide(0, array('mode' => $mode, 'erreur' => "token/charge_id absent dans la reponse", 'log' => var_export($response, true)));
    }
    $id_transaction = $response['id_transaction'];
    $transaction_hash = $response['transaction_hash'];
    if (!($row = sql_fetsel('*', 'spip_transactions', 'id_transaction=' . intval($id_transaction)))) {
        return bank_transaction_invalide($id_transaction, array('mode' => $mode, 'erreur' => "transaction non trouvee", 'log' => var_export($response, true)));
    }
    if ($transaction_hash != $row['transaction_hash']) {
        return bank_transaction_invalide($id_transaction, array('mode' => $mode, 'erreur' => "hash {$transaction_hash} non conforme", 'log' => var_export($response, true)));
    }
    $montant = intval(round(100 * $row['montant'], 0));
    if (strlen($montant) < 3) {
        $montant = str_pad($montant, 3, '0', STR_PAD_LEFT);
    }
    $email = bank_porteur_email($row);
    // ok, on traite le reglement
    $date = $_SERVER['REQUEST_TIME'];
    $date_paiement = date('Y-m-d H:i:s', $date);
    $erreur = "";
    $erreur_code = 0;
    // charger l'API Stripe avec la cle
    stripe_init_api($config);
    // preparer le paiement
    $nom_site = textebrut($GLOBALS['meta']['nom_site']);
    $desc_charge = array('amount' => $montant, "currency" => "eur", "source" => $response['token'], "description" => "Transaction #" . $id_transaction . " [{$nom_site}]", "receipt_email" => $email, "metadata" => array('id_transaction' => $id_transaction, 'id_auteur' => $row['id_auteur'], 'nom_site' => $nom_site, 'url_site' => $GLOBALS['meta']['adresse_site']));
    // la charge existe deja (autoresponse webhook sur abonnement)
    if (isset($response['charge_id']) and $response['charge_id']) {
        try {
            $charge = \Stripe\Charge::retrieve($response['charge_id']);
            $charge->description = $desc_charge['description'];
            $charge->metadata = $desc_charge['metadata'];
            $charge->save();
            if (!$charge->paid) {
                $erreur_code = 'unpaid';
                $erreur = 'payment failed';
            }
        } 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';
            }
        }
    } else {
        // est-ce un abonnement ?
        if ($is_abo) {
            // on decrit l'echeance
            if ($decrire_echeance = charger_fonction("decrire_echeance", "abos", true) and $echeance = $decrire_echeance($id_transaction)) {
                if ($echeance['montant'] > 0) {
                    $montant_echeance = intval(round(100 * $echeance['montant'], 0));
                    if (strlen($montant_echeance) < 3) {
                        $montant_echeance = str_pad($montant_echeance, 3, '0', STR_PAD_LEFT);
                    }
                    $interval = 'month';
                    if (isset($echeance['freq']) and $echeance['freq'] == 'yearly') {
                        $interval = 'year';
                    }
                    $desc_plan = array('amount' => $montant_echeance, 'interval' => $interval, 'name' => "#{$id_transaction} [{$nom_site}]", 'currency' => $desc_charge['currency'], 'metadata' => $desc_charge['metadata']);
                    // dans tous les cas on fait preleve la premiere echeance en paiement unique
                    // et en faisant démarrer l'abonnement par "1 periode" en essai sans paiement
                    // ca permet de gerer le cas paiement initial different, et de recuperer les infos de CB dans tous les cas
                    $time_start = strtotime($date_paiement);
                    $time_paiement_1_interval = strtotime("+1 {$interval}", $time_start);
                    $nb_days = intval(round(($time_paiement_1_interval - $time_start) / 86400));
                    $desc_plan['trial_period_days'] = $nb_days;
                    // un id unique (sauf si on rejoue le meme paiement)
                    $desc_plan['id'] = md5(json_encode($desc_plan) . "-{$transaction_hash}");
                    try {
                        $plan = \Stripe\Plan::retrieve($desc_plan['id']);
                    } catch (Exception $e) {
                        // erreur si on ne retrouve pas le plan, on ignore
                        $plan = false;
                    }
                    try {
                        if (!$plan) {
                            $plan = \Stripe\Plan::create($desc_plan);
                        }
                        if (!$plan) {
                            $erreur = "Erreur creation plan d'abonnement";
                            $erreur_code = "plan_failed";
                        }
                    } 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';
                        }
                    }
                    if ($erreur or $erreur_code) {
                        // regarder si l'annulation n'arrive pas apres un reglement (internaute qui a ouvert 2 fenetres de paiement)
                        if ($row['reglee'] == 'oui') {
                            return array($id_transaction, true);
                        }
                        // sinon enregistrer l'absence de paiement et l'erreur
                        return bank_transaction_echec($id_transaction, array('mode' => $mode, 'config_id' => $config_id, 'date_paiement' => $date_paiement, 'code_erreur' => $erreur_code, 'erreur' => $erreur, 'log' => var_export($response, true)));
                    }
                }
            }
        }
        // essayer de retrouver ou creer un customer pour l'id_auteur
        $customer = null;
        try {
            if ($row['id_auteur']) {
                $customer_id = sql_getfetsel('pay_id', 'spip_transactions', 'pay_id!=' . sql_quote('') . ' AND id_auteur=' . intval($row['id_auteur']) . ' AND statut=' . sql_quote('ok') . ' AND mode=' . sql_quote("{$mode}/{$config_id}"), '', 'date_paiement DESC', '0,1');
                if ($customer_id) {
                    $customer = \Stripe\Customer::retrieve($customer_id);
                }
            }
            // si customer retrouve, on ajoute la source et la transaction
            if ($customer and $customer->email === $email) {
                $customer->source = $desc_charge['source'];
                $metadata = $customer->metadata;
                if (!$metadata) {
                    $metadata = array();
                }
                if (isset($metadata['id_transaction'])) {
                    $metadata['id_transaction'] .= ',' . $id_transaction;
                } else {
                    $metadata['id_transaction'] = $id_transaction;
                }
                $metadata['id_auteur'] = $row['id_auteur'];
                $customer->metadata = $metadata;
                $customer->description = sql_getfetsel('nom', 'spip_auteurs', 'id_auteur=' . intval($row['id_auteur']));
                $customer->save();
            } else {
                $d = array('email' => $email, 'source' => $desc_charge['source'], 'metadata' => $desc_charge['metadata']);
                if ($row['id_auteur']) {
                    $d['description'] = sql_getfetsel('nom', 'spip_auteurs', 'id_auteur=' . intval($row['id_auteur']));
                }
                $customer = \Stripe\Customer::create($d);
            }
            if ($is_abo and !$customer) {
                $erreur = "Erreur creation customer";
                $erreur_code = "cust_failed";
            }
        } 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';
            }
            spip_log("Echec creation/recherche customer transaction #{$id_transaction} {$erreur}", $mode . _LOG_ERREUR);
        }
        if ($is_abo and ($erreur or $erreur_code)) {
            // regarder si l'annulation n'arrive pas apres un reglement (internaute qui a ouvert 2 fenetres de paiement)
            if ($row['reglee'] == 'oui') {
                return array($id_transaction, true);
            }
            // sinon enregistrer l'absence de paiement et l'erreur
            return bank_transaction_echec($id_transaction, array('mode' => $mode, 'config_id' => $config_id, 'date_paiement' => $date_paiement, 'code_erreur' => $erreur_code, 'erreur' => $erreur, 'log' => var_export($response, true)));
        }
        // Create a charge if needed: this will charge the user's card
        try {
            // If we have a Customer
            if ($customer and $customer->id) {
                $desc_charge['customer'] = $customer->id;
                $response['pay_id'] = $customer->id;
                // permet de faire de nouveau paiement sans saisie CB
                unset($desc_charge['source']);
            }
            if ($desc_charge['amount']) {
                $charge = \Stripe\Charge::create($desc_charge);
                // pour les logs en cas d'echec
                $r = $charge->getLastResponse()->json;
                $response = array_merge($response, $r);
                if (!$charge) {
                    $erreur = "Erreur creation charge";
                    $erreur_code = "charge_failed";
                } elseif (!$charge['paid']) {
                    $erreur_code = 'not_paid';
                    $erreur = 'echec paiement stripe';
                    if ($charge['failure_code'] or $charge['failure_message']) {
                        $erreur_code = $charge['failure_code'];
                        $erreur = $charge['failure_message'];
                    }
                }
            }
        } catch (\Stripe\Error\Card $e) {
            // Since it's a decline, \Stripe\Error\Card will be caught
            $body = $e->getJsonBody();
            $err = $body['error'];
            list($erreur_code, $erreur) = stripe_error_code($err);
        } 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';
            }
        }
        // si abonnement : on a un customer et un plan, creer la subscription
        if ($is_abo) {
            if ($plan and $customer) {
                $desc_sub = array('customer' => $customer->id, 'plan' => $plan->id, 'metadata' => array('id_transaction' => $id_transaction));
                try {
                    $sub = \Stripe\Subscription::create($desc_sub);
                    if (!$sub) {
                        $erreur = "Erreur creation subscription";
                        $erreur_code = "sub_failed";
                    } else {
                        $response['abo_uid'] = $sub->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';
                    }
                }
            } else {
                $erreur = "Erreur creation subscription (plan or customer missing)";
                $erreur_code = "sub_failed";
            }
        }
    }
    if ($erreur or $erreur_code) {
        // regarder si l'annulation n'arrive pas apres un reglement (internaute qui a ouvert 2 fenetres de paiement)
        if ($row['reglee'] == 'oui') {
            return array($id_transaction, true);
        }
        // sinon enregistrer l'absence de paiement et l'erreur
        return bank_transaction_echec($id_transaction, array('mode' => $mode, 'config_id' => $config_id, 'date_paiement' => $date_paiement, 'code_erreur' => $erreur_code, 'erreur' => $erreur, 'log' => var_export($response, true)));
    }
    // Ouf, le reglement a ete accepte
    // on verifie que le montant est bon !
    $montant_regle = 0;
    if ($charge) {
        $montant_regle = $charge['amount'] / 100;
    } elseif ($sub) {
        $montant_regle = $sub->plan->amount;
    }
    if ($montant_regle != $row['montant']) {
        spip_log($t = "call_response : id_transaction {$id_transaction}, montant regle {$montant_regle}!=" . $row['montant'] . ":" . var_export($charge, true), $mode);
        // on log ca dans un journal dedie
        spip_log($t, $mode . '_reglements_partiels');
    }
    if ($charge) {
        $transaction = $charge['balance_transaction'];
        $authorisation_id = $charge['id'];
    } elseif ($sub) {
        $transaction = $sub->id;
        $authorisation_id = $plan->id;
    }
    $set = array("autorisation_id" => "{$transaction}/{$authorisation_id}", "mode" => "{$mode}/{$config_id}", "montant_regle" => $montant_regle, "date_paiement" => $date_paiement, "statut" => 'ok', "reglee" => 'oui');
    if (isset($response['pay_id'])) {
        $set['pay_id'] = $response['pay_id'];
    }
    if (isset($response['abo_uid'])) {
        $set['abo_uid'] = $response['abo_uid'];
    }
    // type et numero de carte ?
    if ($charge) {
        if (isset($charge['source']) and $charge['source']['object'] == 'card') {
            // par defaut on note carte et BIN6 dans refcb
            $set['refcb'] = '';
            if (isset($charge['source']['brand'])) {
                $set['refcb'] .= $charge['source']['brand'];
            }
            if (isset($charge['source']['last4']) and $charge['source']['last4']) {
                $set['refcb'] .= ' ****' . $charge['source']['last4'];
            }
            $set['refcb'] = trim($set['refcb']);
            // validite de carte ?
            if (isset($charge['source']['exp_month']) and $charge['source']['exp_year']) {
                $set['validite'] = $charge['source']['exp_year'] . "-" . str_pad($charge['source']['exp_month'], 2, '0', STR_PAD_LEFT);
            }
        }
    }
    $response = array_merge($response, $set);
    // il faudrait stocker le $charge aussi pour d'eventuels retour ?
    sql_updateq("spip_transactions", $set, "id_transaction=" . intval($id_transaction));
    spip_log("call_response : id_transaction {$id_transaction}, reglee", $mode);
    $regler_transaction = charger_fonction('regler_transaction', 'bank');
    $regler_transaction($id_transaction, array('row_prec' => $row));
    return array($id_transaction, true);
}
Exemplo n.º 4
1
 public function delete_plan($stripe_plan)
 {
     try {
         \Stripe\Stripe::setApiKey($this->config->item("stripe_secret_key"));
         $plan = \Stripe\Plan::retrieve($stripe_plan);
         $plan->delete();
         $return['message'] = 'true';
     } 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;
 }
 function delete_plan(WP_REST_Request $request)
 {
     $this->set_api_key();
     $data = $request->get_params();
     if (!isset($data['id'])) {
         return new WP_Error('data', __('No Customer ID Set'), array('status' => 404));
     }
     try {
         $plan = \Stripe\Plan::retrieve($data['id']);
         $plan->delete();
         return new WP_REST_Response($plan, 200);
     } catch (Stripe_AuthenticationError $e) {
         $body = $e->getJsonBody();
         $err = $body['error'];
         return new WP_Error($err['type'], __($err['message']), array('status' => 403));
     } catch (Stripe_Error $e) {
         $body = $e->getJsonBody();
         $err = $body['error'];
         return new WP_Error($err['type'], __($err['message']), array('status' => 403));
     } catch (\Stripe\Error\Base $e) {
         $body = $e->getJsonBody();
         $err = $body['error'];
         return new WP_Error($err['type'], __($err['message']), array('status' => 403));
     }
 }
 function __construct()
 {
     adminGateKeeper();
     $guid = pageArray(2);
     $product = getEntity($guid);
     \Stripe\Stripe::setApiKey(EcommercePlugin::secretKey());
     if ($product->interval != "one_time") {
         try {
             $plan = \Stripe\Plan::retrieve($guid);
             $plan->delete();
         } catch (Exception $e) {
             forward();
         }
     } else {
         if ($product->stripe_sku) {
             $sku = \Stripe\SKU::retrieve($product->stripe_sku);
             $sku->delete();
         }
         if ($product->stripe_product_id) {
             $stripe_product = \Stripe\Product::retrieve($product->stripe_product_id);
             $stripe_product->delete();
         }
     }
     $product->delete();
     new SystemMessage("Your product has been deleted.");
     forward("store");
 }
 function create_plan($amount, $interval, $name, $currency, $id)
 {
     try {
         $create_plan = \Stripe\Plan::create(array("amount" => $amount, "interval" => $interval, "name" => $name, "currency" => $currency, "id" => $id));
         return $create_plan;
     } catch (Exception $e) {
         return $e->getJsonBody();
     }
 }
 /**
  * Check if a plan already exists
  *
  * @param $plan
  * @return bool
  */
 private function planExists($plan)
 {
     try {
         Stripe\Plan::retrieve($plan->id);
         return true;
     } catch (\Exception $e) {
     }
     return false;
 }
Exemplo n.º 9
0
 /**
  * Verify that a plan with a given ID exists, or create a new one if it does
  * not.
  */
 protected static function retrieveOrCreatePlan($id)
 {
     authorizeFromEnv();
     try {
         $plan = Plan::retrieve($id);
     } catch (InvalidRequestError $exception) {
         $plan = Plan::create(array('id' => $id, 'amount' => 0, 'currency' => 'usd', 'interval' => 'month', 'name' => 'Gold Test Plan'));
     }
 }
Exemplo n.º 10
0
 function create_plan()
 {
     try {
         $create_plan = \Stripe\Plan::create(array("amount" => 1000, "interval" => "year", "name" => "Year Suscription Plan", "currency" => "usd", "id" => "year_suscription"));
         return $create_plan;
     } catch (Exception $e) {
         return $e->getJsonBody();
     }
 }
Exemplo n.º 11
0
 public function retrieve_plan($plan_id)
 {
     $result = array('valid' => false);
     try {
         $plan = \Stripe\Plan::retrieve($plan_id);
         $result['plan'] = $plan;
         $result['success'] = true;
     } catch (\Stripe\Error\InvalidRequest $e) {
     }
     return $result;
 }
Exemplo n.º 12
0
 /**
  * @param null $limit
  * @param null $startingAfter
  * @return array|\Stripe\Collection
  */
 public function all($limit = null, $startingAfter = null)
 {
     $data = [];
     if ($limit) {
         $data['limit'] = $limit;
     }
     if ($startingAfter) {
         $data['starting_after'] = $startingAfter;
     }
     $plans = \Stripe\Plan::all($data);
     return $plans;
 }
Exemplo n.º 13
0
function testCreatePlan()
{
    try {
        //self::authorizeFromEnv();
        $planID = 'pro-39';
        $plan = \Stripe\Plan::create(array('amount' => 3900, 'interval' => 'day', 'currency' => 'usd', 'name' => 'Plan', 'id' => $planID));
        echo $plan;
    } catch (Exception $e) {
        $error = $e->getMessage();
        echo $error;
    }
}
Exemplo n.º 14
0
 /**
  * {@inheritDoc}
  */
 public function execute($request)
 {
     /** @var $request CreatePlan */
     RequestNotSupportedException::assertSupports($this, $request);
     $model = ArrayObject::ensureArrayObject($request->getModel());
     try {
         Stripe::setApiKey($this->keys->getSecretKey());
         $plan = Plan::create($model->toUnsafeArrayWithoutLocal());
         $model->replace($plan->__toArray(true));
     } catch (Error\Base $e) {
         $model->replace($e->getJsonBody());
     }
 }
Exemplo n.º 15
0
 private static function getStripePlans()
 {
     Stripe::setApiKey(Config::get('services.stripe.secret'));
     $plans = StripePlan::all();
     if (!$plans) {
         return false;
     }
     self::$items = [];
     foreach ($plans->data as $plan) {
         $item = $plan->__toArray();
         if ($item['amount'] > 0) {
             $item['amount'] = $item['amount'] / 100;
         }
         self::$items[] = $item;
     }
 }
 /**
  * Creates a subscription for the currently Authenticated user, provided they are first
  * at least a member of the site.
  *
  * Once a subscription is created, it also creates a payment model for that user and upgrades
  * their role to 'Susbcriber'.
  *
  * @param string $token    The user subscription token from Stripe.
  */
 public function createSubscription($token)
 {
     // It makes no sense to try and give a subscription to someone who
     // is not a member
     if (Auth::isMember()) {
         // Subscribe the user
         Auth::user()->subscription($this->currentPlan)->create($token);
         $subscriptionEndsAt = Auth::user()->subscription()->getSubscriptionEndDate();
         // Create a payment representation
         Payment::create(['user_id' => Auth::id(), 'price' => Plan::retrieve($this->currentPlan)->amount, 'subscription_ends_at' => $subscriptionEndsAt]);
         // Set the user to the subscriber role
         Auth::user()->role_id = UserRole::Subscriber;
         Auth::user()->subscription_ends_at = $subscriptionEndsAt;
         Auth::user()->trial_ends_at = null;
         Auth::user()->save();
     }
 }
 function __construct()
 {
     adminGateKeeper();
     \Stripe\Stripe::setApiKey(EcommercePlugin::secretKey());
     $container_guid = getInput("container_guid");
     $title = getInput("title");
     $description = getInput('description');
     $interval = getInput("interval");
     $price = getInput("price");
     $product = new Product();
     $product->title = $title;
     $product->description = $description;
     $product->price = $price;
     $product->container_guid = $container_guid;
     $product->interval = $interval;
     $product->access_id = "public";
     $product->save();
     $product->createAvatar();
     if (isset($_FILES["download"]) && $_FILES["download"]["name"]) {
         $file = new File();
         $file->access_id = "product";
         $file->container_guid = $product->guid;
         $guid = $file->save();
         uploadFile("download", $guid, array("zip"));
         $product->download = $guid;
     }
     if ($interval != "one_time") {
         $stripe_plan = \Stripe\Plan::create(array("amount" => $price * 100, "interval" => $interval, "name" => $title, "currency" => "usd", "id" => $product->guid));
         $id = $stripe_plan->id;
         $product->stripe_id = $id;
         $product->save();
     } else {
         // Create product and SKU in stripe
         $stripe_product = \Stripe\Product::create(array("name" => $product->title, "description" => $product->description, "shippable" => false));
         $product->stripe_product_id = $stripe_product->id;
         // Create SKU
         $stripe_sku = \Stripe\SKU::create(array("product" => $stripe_product->id, "price" => $product->price * 100, "currency" => "usd", "inventory" => array("type" => "infinite"), "metadata" => array("guid" => $product->guid)));
         $product->stripe_sku = $stripe_sku->id;
         $product->save();
     }
     new SystemMessage("Your product has been saved.");
     forward("store");
 }
Exemplo n.º 18
0
 public function actionSubscription()
 {
     $request = \Yii::$app->request;
     $Stripe = \Yii::$app->getModule('stripe');
     if (\Yii::$app->hasModule('stripe')) {
         if (\Stripe\Plan::retrieve("gold")) {
         } else {
             \Stripe\Plan::create(array("amount" => $subscription_amount, "interval" => "month", "name" => "Gold Plan", "currency" => "usd", "id" => "gold"));
         }
         $msg = "Error In Coennecting to stripe! Please try again later";
         if (!empty($request->post('stripeToken'))) {
             $token = $request->post('stripeToken');
             $membership = $request->post('membership');
             if (!empty($membership) && $membership == 'on') {
                 try {
                     $customer = \Stripe\Customer::create(array("description" => "Customer for test@example.com", "source" => $token));
                     $customer = \Stripe\Customer::retrieve($customer->id);
                     $customer_res = $customer->subscriptions->create(array("plan" => "gold"));
                 } catch (\Stripe\Error\Card $e) {
                 }
             } else {
                 try {
                     $charge = \Stripe\Charge::create(array("amount" => $subscription_amount, "currency" => "usd", "source" => $token, "description" => "Example charge"));
                 } catch (\Stripe\Error\Card $e) {
                 }
             }
             if (!empty($charge)) {
                 if ($charge->paid == true) {
                     $Subscription = new Subscription();
                     $Subscription->appointment_id = \Yii::$app->session['apid'];
                     $Subscription->amount_paid = $charge->amount;
                     $Subscription->currency = $charge->currency;
                     $Subscription->user_id = \Yii::$app->user->id;
                     $Subscription->membership = 0;
                     $Subscription->transaction_id = $charge->id;
                     $Subscription->payment_type = $charge->source->brand;
                     $Subscription->save();
                     unset(\Yii::$app->session['apid']);
                     $msg = "<h1>You Subscribed Successfully Thank You</h1>";
                 } else {
                     $msg = "<h1>Error Please try again</h1>";
                 }
             } else {
                 if (!empty($customer)) {
                     if ($customer_res->status == "active" && (!empty($membership) && $membership == 'on')) {
                         $Subscription = new Subscription();
                         $Subscription->appointment_id = \Yii::$app->session['apid'];
                         $Subscription->amount_paid = $customer_res->amount;
                         $Subscription->currency = $customer_res->currency;
                         $Subscription->user_id = \Yii::$app->user->id;
                         $Subscription->membership = 1;
                         $Subscription->transaction_id = $customer_res->id;
                         $Subscription->payment_type = $customer->sources->data[0]->brand;
                         $Subscription->save();
                         unset(\Yii::$app->session['apid']);
                         $msg = "<h1>You Subscribed Successfully Thank You</h1>";
                     } else {
                     }
                 } else {
                     $msg = "<h1>Please Fill Appoinment Form</h1>";
                 }
             }
         }
     } else {
         $msg = "<h1>Stripe is not configured correctly,Please contact administrator</h1>";
     }
     return $this->render("subscription", array('msg' => $msg));
 }
Exemplo n.º 19
0
 public function getPlan($id = '')
 {
     return \Stripe\Plan::retrieve($id);
 }
Exemplo n.º 20
0
 public function update(array $data)
 {
     $plan = Plan::retrieve($data['slug']);
     $plan->name = $data['name'];
     $plan->save();
 }
Exemplo n.º 21
0
 /**
  * @param null|array $periods
  */
 public function deleteStripePlans($periods = null)
 {
     $paymentGateway = Payment_gateways::findOneActiveBySlug('stripe');
     \Stripe\Stripe::setApiKey($paymentGateway->getFieldValue('apiKey'));
     foreach ($periods as $period) {
         try {
             $plan = \Stripe\Plan::retrieve($period->id);
             $plan->delete();
         } catch (Exception $e) {
         }
     }
 }
Exemplo n.º 22
0
 function generate_payload()
 {
     $payload = array('description' => "Donation from " . $_POST['email'], 'card' => $_POST['stripeToken'], 'metadata' => array_merge(array('email' => htmlspecialchars($_POST['email']))));
     \Stripe\Stripe::setApiKey($this->stripe_private_key);
     try {
         $plan = \Stripe\Plan::retrieve($_POST['plan']);
     } catch (\Stripe\Error\Base $e) {
         $plan = null;
     } catch (Exception $e) {
         $plan = null;
     }
     if ($plan) {
         $payload['plan'] = $_POST['plan'];
         $payload['email'] = $_POST['email'];
         if ($_POST['plan'] == 'monthly_custom') {
             $payload['quantity'] = $_POST['custom_amount'];
         } else {
             $payload['quantity'] = 1;
         }
     } else {
         $payload['currency'] = $_POST['currency'];
         $payload['receipt_email'] = $_POST['email'];
         if (!in_array(strtolower($payload['currency']), self::$zero_decimal_currencies)) {
             $payload['amount'] = $_POST['amount'] * 100;
         } else {
             $payload['amount'] = $_POST['amount'];
         }
     }
     return $payload;
 }
 /**
  * Determine if a plan exists
  *
  * @since 2.1
  * @param $plan | The name of the plan to check
  * @return bool | string false if the plan doesn't exist, plan id if it does
  */
 private function plan_exists($plan)
 {
     \Stripe\Stripe::setApiKey($this->secret_key);
     if (!($plan = rcp_get_subscription_details_by_name($plan))) {
         return false;
     }
     // fallback to old plan id if the new plan id does not exist
     $old_plan_id = strtolower(str_replace(' ', '', $plan->name));
     $new_plan_id = sprintf('%s-%s-%s', $old_plan_id, $plan->price, $plan->duration . $plan->duration_unit);
     // check if the plan new plan id structure exists
     try {
         $plan = \Stripe\Plan::retrieve($new_plan_id);
         return $plan->id;
     } catch (Exception $e) {
     }
     try {
         // fall back to the old plan id structure and verify that the plan metadata also matches
         $stripe_plan = \Stripe\Plan::retrieve($old_plan_id);
         if ((int) $stripe_plan->amount !== (int) $plan->price * 100) {
             return false;
         }
         if ($stripe_plan->interval !== $plan->duration_unit) {
             return false;
         }
         if ($stripe_plan->interval_count !== intval($plan->duration)) {
             return false;
         }
         return $old_plan_id;
     } catch (Exception $e) {
         return false;
     }
 }
Exemplo n.º 24
0
 protected function doAdd($data)
 {
     if (empty($this->list_route)) {
         throw new \Exception('Must define a route for listing the items');
     }
     if (empty($this->create_item_route)) {
         throw new \Exception('Must define a route for creating the item');
     }
     if (empty($this->edit_item_route)) {
         throw new \Exception('Must define a route for editing the item');
     }
     if (!isset($data['submitType'])) {
         $data['submitType'] = "save_edit";
     }
     $f3 = \Base::instance();
     $flash = \Dsc\Flash::instance();
     $model = $this->getModel();
     // save
     try {
         $values = $data;
         $create = array_filter($values['stripe']);
         //make a method for this, convert float to cents
         $create['amount'] = (int) $create['amount'];
         $settings = \Striper\Models\Settings::fetch();
         // Set your secret key: remember to change this to your live secret key in production
         // See your keys here https://manage.stripe.com/account
         \Stripe\Stripe::setApiKey($settings->{$settings->mode . '.secret_key'});
         $plan = \Stripe\Plan::create($create);
         $values['stripe'] = array('id' => $plan->id, 'name' => $plan->name, 'created' => $plan->created, 'amount' => $plan->amount, 'interval' => $plan->interval, 'currency' => $plan->currency, 'interval_count' => $plan->interval_count, 'trial_period_days' => $plan->trial_period_days);
         unset($values['submitType']);
         //\Dsc\System::instance()->addMessage(\Dsc\Debug::dump($values), 'warning');
         $this->item = $model->create($values);
     } catch (\Exception $e) {
         \Dsc\System::instance()->addMessage('Save failed with the following errors:', 'error');
         \Dsc\System::instance()->addMessage($e->getMessage(), 'error');
         if (\Base::instance()->get('DEBUG')) {
             \Dsc\System::instance()->addMessage($e->getTraceAsString(), 'error');
         }
         if ($f3->get('AJAX')) {
             // output system messages in response object
             return $this->outputJson($this->getJsonResponse(array('error' => true, 'message' => \Dsc\System::instance()->renderMessages())));
         }
         // redirect back to the create form with the fields pre-populated
         \Dsc\System::instance()->setUserState('use_flash.' . $this->create_item_route, true);
         $flash->store($data);
         $this->setRedirect($this->create_item_route);
         return false;
     }
     // redirect to the editing form for the new item
     \Dsc\System::instance()->addMessage('Item saved', 'success');
     if (method_exists($this->item, 'cast')) {
         $this->item_data = $this->item->cast();
     } else {
         $this->item_data = \Joomla\Utilities\ArrayHelper::fromObject($this->item);
     }
     if ($f3->get('AJAX')) {
         return $this->outputJson($this->getJsonResponse(array('message' => \Dsc\System::instance()->renderMessages(), 'result' => $this->item_data)));
     }
     switch ($data['submitType']) {
         case "save_new":
             $route = $this->create_item_route;
             break;
         case "save_close":
             $route = $this->list_route;
             break;
         default:
             $flash->store($this->item_data);
             $id = $this->item->get($this->getItemKey());
             $route = str_replace('{id}', $id, $this->edit_item_route);
             break;
     }
     $this->setRedirect($route);
     return $this;
 }
Exemplo n.º 25
0
 /**
  * Retrieve stripe plan
  *
  * @param string $id Plan StripeID
  *
  * @return \Stripe\Plan
  */
 public function retrieve($id)
 {
     return StripePlanApi::retrieve($id);
 }
Exemplo n.º 26
0
 public function createPlan(StripePlanRequest $request)
 {
     /*
      * Stripe Api Key Set
      * This ApiKey get from environment variable
      * Using Stripe lib for creating plan
      * */
     /*
      * Processing input data for stripe
      * */
     $amount = number_format($request->plan_amount, 2);
     $amount = (int) ($amount * 100);
     $interval = strtolower($request->plan_interval);
     $interval_count = 1;
     if ($interval == 'custom') {
         $interval_count = (int) $request->interval_count;
         $interval = $request->coustom_interval;
     } else {
         if ($interval == '3-month' || $interval == '6-month') {
             $array = explode('-', $interval);
             $interval_count = (int) $array[0];
             $interval = $array[1];
         }
     }
     Stripe::setApiKey(getenv('STRIPE_SECRET'));
     $plan = Plan::create(array("id" => $request->plan_id, "name" => $request->plan_name, "currency" => $request->plan_currency, "amount" => $amount, "interval" => $interval, "interval_count" => $interval_count, "trial_period_days" => (int) $request->plan_trial, "statement_descriptor" => $request->plan_des));
     /*
      * Stripe Plan insert in Local Database
      * Using Local Database for faster loading
      * */
     $stripePlan = StripePlan::create(["plan_id" => $request->plan_id, "name" => $request->plan_name, "amount" => $request->plan_amount, "currency" => $request->plan_currency, "interval" => $interval, "interval_count" => $interval_count, "auto_renewal" => (int) $request->auto_renewal ? $request->auto_renewal : 0, "trial_period_days" => (int) $request->plan_trial, "statement_descriptor" => $request->plan_des, "coupon_id" => $request->discount == 1 ? $request->stripe_coupon : null, "created" => date('Y-m-d H:i:s')]);
     $stripePlan->planFeature()->attach($request->feature_id);
     if ($stripePlan) {
         flash('Your Plan (' . $stripePlan->name . ') is successfully created.');
     } else {
         flash('Your Plan (' . $stripePlan->name . ') is failed to create. Please contact your administrator for assistance.');
     }
     return redirect()->back();
 }
 /**
  * Determine if a plan exists
  *
  * @since 2.1
  * @return bool
  */
 private function plan_exists($plan_id = '')
 {
     $plan_id = strtolower(str_replace(' ', '', $plan_id));
     \Stripe\Stripe::setApiKey($this->secret_key);
     try {
         $plan = \Stripe\Plan::retrieve($plan_id);
         return true;
     } catch (Exception $e) {
         return false;
     }
 }
function musof_stripe_checkout()
{
    global $ultimatemember;
    $user_id = get_current_user_id();
    $theme = get_stylesheet_directory_uri();
    //@TODO reload cache
    $role = $ultimatemember->user->profile['role'];
    $ajax_url = admin_url('/admin-ajax.php');
    echo '<div class="um-account-heading uimob340-hide uimob500-hide"><i class="um-faicon-star"></i>Pro Membership</div>';
    if ($role != 'pro-member') {
        $plans_data = array();
        require dirname(__FILE__) . '/stripe-php/init.php';
        \Stripe\Stripe::setApiKey("sk_test_P7kUSLtvnEa1JLzaJyk7GGIX");
        $plans = \Stripe\Plan::all(array("limit" => 3));
        $plans = $plans->__toArray(true);
        foreach ($plans['data'] as $plan) {
            $plans_data[$plan['id']] = $plan['amount'];
        }
        echo <<<FREE
\t\t<div class="um-field um-field-user_pro" data-key="user_pro">

\t\t<script src="https://checkout.stripe.com/checkout.js"></script>
\t\t<p>Upgrade to pro membership:</p>
\t\t<a class="button" id="pro-yearly">Pay Annually</a>
\t\t<a class="button" id="pro-monthly">Pay Monthly</a>
\t\t<style>
\t#musof_payment_processing, #musof_payment_processing img {
\t\tmargin: auto;
\t\tbottom: 0;
\t\ttop: 0;
\t\tleft: 0;
\t\tright: 0;
\t\tbackground-color: rgba(255,255,255,0.8);
\t\tposition: fixed;
\t}
\t</style>
\t<div id="musof_payment_processing" style="display:none;">
\t<img src="https://cdnjs.cloudflare.com/ajax/libs/file-uploader/3.7.0/processing.gif">
\t</div>
\t
\t<script>
\t(function(\$) {
\t\tvar name = 'Muso Net Ltd',
\t\tcurrency = "usd",
\t\tplan = 'pro-monthly',
\t\turl = window.location.origin + window.location.pathname;
\t\tvar handler = StripeCheckout.configure({
\t\t\tkey: 'pk_test_PxOWZ6rBgc7dmckuYUx24bnO',
\t\t\timage: '{$theme}/images/muso-square.png',
\t\t\tlocale: 'auto',
\t\t\ttoken: function(token) {
\t\t\t\tquery = {};
\t\t\t\tquery.action = 'musof_pro';
\t\t\t\tquery.description = description;
\t\t\t\tquery.currency = currency;
\t\t\t\tquery.amount = amount;
\t\t\t\tquery.plan = plan;
\t\t\t\tquery.tokenData = token;
\t\t\t\tquery.token = token.id;
\t\t\t\tjQuery.post( '{$ajax_url}', query, function ( response ) {
\t\t\t\t\tconsole.log( response );
\t\t\t\t\tif ( 'Payment successful' == response ) {
\t\t\t\t\t\tconsole.log( 'Success!!!' );
\t\t\t\t\t\twindow.location = url + '?updated=payment-successful';
\t\t\t\t\t} else {
\t\t\t\t\t\tconsole.log( 'Error!' );
\t\t\t\t\t\tresponse = JSON.parse( response );
\t\t\t\t\t\tconsole.log( response );
\t\t\t\t\t}
\t\t\t\t} );
}
});

\$('#pro-yearly').on('click', function(e) {
\tdescription = 'yearly';
\tamount = {$plans_data['pro-yearly']};
\tplan = 'pro-yearly';
\t\t    // Open Checkout with further options
\thandler.open({
\t\tname: name,
\t\tdescription: description,
\t\tcurrency: currency,
\t\tamount: amount
\t});
e.preventDefault();
});

\$('#pro-monthly').on('click', function(e) {
    // Open Checkout with further options
\tdescription = 'monthly';
\tamount = {$plans_data['pro-monthly']};
\tplan = 'pro-monthly';
\thandler.open({
\t\tname: name,
\t\tdescription: description,
\t\tcurrency: currency,
\t\tamount: amount
\t});
e.preventDefault();
});
\t\t// Close Checkout on page navigation
\$(window).on('popstate', function() {
\tconsole.log( 'popstate' );
\t\$('#musof_payment_processing').show();
\thandler.close();
});

})(jQuery);
</script>

</div>
FREE;
    } else {
        $payment_log = get_user_meta($user_id, 'musof_payment_log', true);
        echo <<<PRO
\t<p id='member-status'>You are a Pro Memeber
\t<a href='?cancel-membership={$user_id}'>Cancel Membership</a>
\t</p>
\t
\t<style>
\tmember-status
\t\t#tbl-header {
\tfont-size: 15px !important;
\tline-height: 22px !important;
\tfont-weight: 600;
}
\t\t#pay-history-tbl th {
font-size: 12px !important;
line-height: 22px !important;
font-weight: 600;
padding-left: 20px;
padding-top: 20px;
}\t
</style>

PRO;
        if (!empty($_GET['cancel-membership'])) {
            musof_membership_cancel();
        }
        echo '</table>';
    }
    /*
    	$payment_log = get_user_meta($user_id, 'musof_payment_log', true);
    	$payment_log = $payment_log ? $payment_log : array();
    
    	foreach ($payment_log as $time => $value) {
    
    		print_r($value);
    	}
    * 
    */
}
Exemplo n.º 29
0
 /**
  * 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];
 }
 /**
  * updatePlans
  * --------------------------------------------------
  * Updating the current stripe Plans.
  * @returns The stripe plans.
  * @throws StripeNotConnected
  * --------------------------------------------------
  */
 public function updatePlans()
 {
     // Connecting to stripe, and making query.
     try {
         $decodedData = json_decode($this->loadJSON(\Stripe\Plan::all()), TRUE);
     } catch (\Stripe\Error\Authentication $e) {
         // Access token expired. Calling handler.
         $this->getNewAccessToken();
     }
     // Getting the plans.
     $plans = [];
     foreach ($decodedData['data'] as $plan) {
         $new_plan = new StripePlan(array('plan_id' => $plan['id'], 'name' => $plan['name'], 'currency' => $plan['currency'], 'amount' => $plan['amount'], 'interval' => $plan['interval'], 'interval_count' => $plan['interval_count']));
         $new_plan->user()->associate($this->user);
         array_push($plans, $new_plan);
     }
     // Delete old, save new.
     foreach (StripePlan::where('user_id', $this->user->id)->get() as $stripePlan) {
         StripeSubscription::where('plan_id', $stripePlan->id)->delete();
         $stripePlan->delete();
     }
     foreach ($plans as $plan) {
         $plan->save();
     }
     return $plans;
 }