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; } }
/** * 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); }
public function create(array $data) { try { Plan::create(array('amount' => $data['amount'], 'interval' => $data['interval'], 'name' => $data['name'], 'currency' => 'usd', 'id' => $data['id'])); } catch (Exception $e) { } }
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(); } }
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(); } }
/** * 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')); } }
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; } }
/** * {@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()); } }
/** * Execute the console command. * * @return mixed */ public function handle() { Stripe\Stripe::setApiKey(config('services.stripe.secret')); $plans = Spark::$teamPlans; foreach ($plans as $plan) { if ($this->planExists($plan)) { $this->info('Stripe plan ' . $plan->id . ' already exists'); } else { Stripe\Plan::create(['id' => $plan->id, 'name' => Spark::$details['product'] . ' ' . $plan->name . ' ($' . $plan->price . ' ' . $plan->interval . ')', 'amount' => $plan->price * 100, 'interval' => str_replace('ly', '', $plan->interval), 'currency' => 'usd', 'statement_descriptor' => Spark::$details['vendor'], 'trial_period_days' => $plan->trialDays]); $this->info('Stripe plan created: ' . $plan->id); } } $this->info('Finished'); }
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"); }
/** * Create plan in Stripe * * @since 2.1 * @return bool | string - plan_id if successful, false if not */ private function create_plan($plan_name = '') { global $rcp_options; // get all subscription level info for this plan $plan = rcp_get_subscription_details_by_name($plan_name); $price = round($plan->price * rcp_stripe_get_currency_multiplier(), 0); $interval = $plan->duration_unit; $interval_count = $plan->duration; $name = $plan->name; $plan_id = sprintf('%s-%s-%s', strtolower(str_replace(' ', '', $plan_name)), $plan->price, $plan->duration . $plan->duration_unit); $currency = strtolower($rcp_options['currency']); \Stripe\Stripe::setApiKey($this->secret_key); try { $plan = \Stripe\Plan::create(array("amount" => $price, "interval" => $interval, "interval_count" => $interval_count, "name" => $name, "currency" => $currency, "id" => $plan_id)); // plann successfully created return $plan->id; } catch (Exception $e) { $this->handle_processing_error($e); } }
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; }
public function create_plan($stripe_plan, $plan_name, $plan_amount) { try { \Stripe\Stripe::setApiKey($this->config->item("stripe_secret_key")); $response = \Stripe\Plan::create(array("amount" => $plan_amount, "interval" => "month", "name" => $plan_name, "currency" => "usd", "id" => $stripe_plan)); $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; }
/** * Create and return a Stripe plan with the specified properties. * * @param string $plan_id The plan ID. * @param array $feed The feed currently being processed. * @param float|int $payment_amount The recurring amount. * @param int $trial_period_days The number of days the trial should last. * @param string $currency The currency code for the entry being processed. * * @return \Stripe\Plan */ public function create_plan($plan_id, $feed, $payment_amount, $trial_period_days, $currency) { // Prepare plan metadata. $plan_meta = array('interval' => $feed['meta']['billingCycle_unit'], 'interval_count' => $feed['meta']['billingCycle_length'], 'name' => $feed['meta']['feedName'], 'currency' => $currency, 'id' => $plan_id, 'amount' => $this->get_amount_export($payment_amount, $currency), 'trial_period_days' => $trial_period_days); // Log the plan to be created. $this->log_debug(__METHOD__ . '(): Plan to be created => ' . print_r($plan_meta, 1)); // Create Stripe plan. $plan = \Stripe\Plan::create($plan_meta); return $plan; }
/** * Create plan in Stripe * * @since 2.1 * @return bool */ private function create_plan($plan_name = '') { global $rcp_options; // get all subscription level info for this plan $plan = rcp_get_subscription_details_by_name($plan_name); $price = $plan->price * 100; $interval = $plan->duration_unit; $interval_count = $plan->duration; $name = $plan->name; $plan_id = strtolower(str_replace(' ', '', $plan_name)); $currency = strtolower($rcp_options['currency']); \Stripe\Stripe::setApiKey($this->secret_key); try { \Stripe\Plan::create(array("amount" => $price, "interval" => $interval, "interval_count" => $interval_count, "name" => $name, "currency" => $currency, "id" => $plan_id)); // plann successfully created return true; } catch (Exception $e) { // there was a problem return false; } }
/** * 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)); }
/** * Create plans in Stripe. */ public function createStripePlans() { $paymentGateway = Payment_gateways::findOneActiveBySlug('stripe'); \Stripe\Stripe::setApiKey($paymentGateway->getFieldValue('apiKey')); foreach ($this->getPeriods() as $period) { try { \Stripe\Plan::create(array('amount' => $period->price, 'interval' => "month", 'name' => $this->name . ' (' . $period->period . ' months)', 'currency' => "usd", 'id' => $period->id, 'interval_count' => $period->period)); } catch (Exception $e) { try { $plan = \Stripe\Plan::retrieve($period->id); $plan->name = $this->name . ' (' . $period->period . ' months)'; $plan->save(); } catch (Exception $e) { } } } }
/** * Create stripe plan * * @param StripePlanModel $plan * * @return \Stripe\Plan */ public function create(StripePlanModel $plan) { return StripePlanApi::create($plan->toArray()); }
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(); }
/** * Create a plan * * @param array $params * * @return Plan */ public function create_plan($params = array()) { return Plan::create($params); }