retrieve() public static method

public static retrieve ( string $id, array | string | null $opts = null ) : Plan
$id string The ID of the plan to retrieve.
$opts array | string | null
return Plan
 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;
     }
 }
Esempio 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');
     }
 }
Esempio 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);
}
Esempio 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");
 }
Esempio n. 7
0
 /**
  * @param $id
  * @return Plan
  */
 public function get($id = null)
 {
     if (!$id) {
         $id = $this->planId;
     }
     $pd = \Stripe\Plan::retrieve($id);
     return $pd;
 }
 /**
  * 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;
 }
Esempio 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'));
     }
 }
Esempio n. 10
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;
 }
 /**
  * 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();
     }
 }
 public function getPlan($id = '')
 {
     return \Stripe\Plan::retrieve($id);
 }
 /**
  * Try and retrieve the plan if a plan with the matching id has previously been created.
  *
  * @param string $plan_id The subscription plan id.
  *
  * @return array|bool
  */
 public function get_plan($plan_id)
 {
     try {
         // Get Stripe plan.
         $plan = \Stripe\Plan::retrieve($plan_id);
     } catch (\Exception $e) {
         /**
          * There is no error type specific to failing to retrieve a subscription when an invalid plan ID is passed. We assume here
          * that any 'invalid_request_error' means that the subscription does not exist even though other errors (like providing
          * incorrect API keys) will also generate the 'invalid_request_error'. There is no way to differentiate these requests
          * without relying on the error message which is more likely to change and not reliable.
          */
         // Get error response.
         $response = $e->getJsonBody();
         // If error is an invalid request error, return error message.
         if (rgars($response, 'error/type') !== 'invalid_request_error') {
             $plan = $this->authorization_error($e->getMessage());
         } else {
             $plan = false;
         }
     }
     return $plan;
 }
 /**
  * Get a plan
  *
  * @param $plan_id
  *
  * @return Plan
  */
 public function get_plan($plan_id)
 {
     try {
         return Plan::retrieve($plan_id);
     } catch (\Stripe\Error\InvalidRequest $e) {
         return false;
     }
 }
Esempio n. 15
0
 public function update(array $data)
 {
     $plan = Plan::retrieve($data['slug']);
     $plan->name = $data['name'];
     $plan->save();
 }
 /**
  * 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;
     }
 }
 /**
  * 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;
     }
 }
Esempio n. 18
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) {
         }
     }
 }
Esempio n. 19
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;
 }
Esempio n. 20
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];
 }
 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));
 }
Esempio n. 22
0
 public function plan()
 {
     $user = $this->session->user();
     // When the user isn't a Stripe customer, we need to get a payment method from them and a token...
     if (!$user->isStripeCustomer()) {
         AppController::redirect(RouteController::fqURL('subscription.payment'));
     }
     if ($this->request->isPOST()) {
         $post = $this->request->postData();
         if (!empty($post['plan'])) {
             try {
                 \Stripe\Stripe::setApiKey(AppConfig::getValue('stripe_secret_api_key'));
                 // Fetch the Customer Object
                 $customer = $this->getCustomer($user);
                 // Validate the Plan
                 $plan = \Stripe\Plan::retrieve($post['plan']);
                 // Validate a Coupon
                 if (!empty($post['coupon'])) {
                     $coupon = \Stripe\Coupon::retrieve($post['coupon']);
                 }
                 // Are we updating an existing subscription?
                 if ($customer->subscriptions->total_count > 0) {
                     // Update/Change Subscription
                     $subscription = $customer->subscriptions->retrieve($customer->subscriptions->data[0]->id);
                     $subscription->plan = $plan->id;
                     $subscription->coupon = isset($coupon) ? $coupon->id : null;
                     $subscription->save();
                 } else {
                     // New Subscription
                     $customer->subscriptions->create(['plan' => $plan->id, 'coupon' => isset($coupon) ? $coupon->id : null], ['idempotency_key' => hash('sha256', $customer->id . $customer->subscriptions->data[0]->plan->id . $plan->id)]);
                 }
                 // Update User (internal)
                 $user->subscription = $plan->name;
                 $user->save();
                 // Done, Redirect...
                 AppController::redirect(addQueryParams(RouteController::fqURL('subscription.manage'), ['status' => 'plan-added']));
             } catch (\Stripe\Error\Card $exception) {
                 $this->logStripeException($exception, (string) $this->request->queryArgValue('token'));
             } catch (\Stripe\Error\InvalidRequest $exception) {
                 $this->logStripeException($exception, (string) $this->request->queryArgValue('token'));
             } catch (\Stripe\Error\Authentication $exception) {
                 $this->logStripeException($exception, (string) $this->request->queryArgValue('token'));
             } catch (\Stripe\Error\ApiConnection $exception) {
                 $this->logStripeException($exception, (string) $this->request->queryArgValue('token'));
             } catch (\Stripe\Error\Base $exception) {
                 $this->logStripeException($exception, (string) $this->request->queryArgValue('token'));
             }
         } else {
             AppController::fatalError('plan (required) was missing from the request');
         }
     } else {
         // Fetch Plans (only use required data)
         foreach ($this->getAvailablePlans()['data'] as $plan) {
             $planList[] = ['id' => $plan->id, 'name' => $plan->name, 'amount' => $plan->amount, 'currency' => $plan->currency, 'interval' => $plan->interval, 'interval_count' => $plan->interval_count];
         }
         if (isset($planList) && count($planList)) {
             // Sort by Amount (ASC)
             usort($planList, function ($a, $b) {
                 return $a['amount'] > $b['amount'];
             });
         }
     }
     $this->view = new HTMLView();
     $this->view->includeTemplate('subscription.plan', ['app_name' => AppConfig::getValue('app_name'), 'plans' => isset($planList) ? $planList : null]);
     $this->view->render(true);
 }
Esempio n. 23
0
 /**
  * Retrieve stripe plan
  *
  * @param string $id Plan StripeID
  *
  * @return \Stripe\Plan
  */
 public function retrieve($id)
 {
     return StripePlanApi::retrieve($id);
 }