예제 #1
1
 /**
  * Create and send the request
  * 
  * @param array $options array of options to be send in POST request
  * @return gateway_response response object
  * 
  */
 public function send($options, $type = '')
 {
     $result = '';
     try {
         if ($type == 'subscription') {
             $result = Stripe_Customer::create($options);
         } elseif ($type == 'plan') {
             $result = Stripe_Plan::create($options);
         } elseif ($type == 'retrieve') {
             $result = Stripe_Plan::retrieve($options);
         } elseif ($type == 'customer') {
             $result = Stripe_Customer::create($options);
         } elseif ($type == 'invoice') {
             $result = Stripe_InvoiceItem::create($options);
             // Stripe_Customer::invoiceItems($options);
         } elseif ($type == 'cancel') {
             $cu = Stripe_Customer::retrieve($options['customer']);
             $result = $cu->cancelSubscription();
         } else {
             $result = Stripe_Charge::create($options);
         }
     } catch (Exception $ex) {
         $result = $ex;
     }
     $response = new stripe_response($result);
     return $response;
 }
예제 #2
1
 public function indexAction(Request $request, $id)
 {
     // Vérifier que l'utilisateur a le droit de supprimer ce contrat
     // Set your secret key: remember to change this to your live secret key in production
     // See your keys here https://dashboard.stripe.com/account/apikeys
     $request = $this->container->get('request');
     $message = '';
     if ($request->isMethod('POST')) {
         \Stripe::setApiKey('sk_test_GyiB2fCxy62ydudovWhyyp6H');
         $token = $request->get('stripeToken');
         $customer = \Stripe_Customer::create(array('email' => '*****@*****.**', 'card' => $token));
         $charge = \Stripe_Charge::create(array('customer' => $customer->id, 'amount' => 700, 'currency' => 'eur'));
         return $this->redirectToRoute("app_front_office_resiliation_preview", array("id" => $id));
     }
     return $this->render('AppFrontOfficeBundle:Payment:index.html.twig', array("message" => $message));
 }
예제 #3
0
파일: pay.php 프로젝트: eavesmonkey/respond
 /**
  * @method POST
  */
 function pay()
 {
     // parse request
     parse_str($this->request->data, $request);
     $token = $request['token'];
     $plan = $request['plan'];
     // get an authuser
     $authUser = new AuthUser();
     if (isset($authUser->UserUniqId)) {
         // check if authorized
         Stripe::setApiKey(STRIPE_API_KEY);
         // create a new customer and subscribe them to the plan
         $customer = Stripe_Customer::create(array("card" => $token, "plan" => $plan, "email" => $authUser->Email));
         // get back the id and the end period for the plan
         $id = $customer->id;
         $end = $customer->subscription->current_period_end;
         // #debug print 'end='.$end;
         date_default_timezone_set('UTC');
         // create a date from the timestamp returned by Stripe
         $renewalDate = gmdate("Y-m-d H:i:s", intval($end));
         // #debug print ' renewalDate='.$renewalDate;
         // by default, you should not have to update a payment
         $updatePayment = 0;
         // update the db and session
         Site::SetSubscription($authUser->SiteUniqId, $plan, $id, $renewalDate, $updatePayment);
         AuthUser::SetPlan($plan, $renewalDate, $updatePayment);
         // return a json response
         return new Tonic\Response(Tonic\Response::OK);
     } else {
         return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
     }
 }
예제 #4
0
 public function confirm()
 {
     $this->load->model('checkout/order');
     $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
     $amount = (int) ($this->currency->format($order_info['total'], $order_info['currency_code'], 1.0, false) * 100);
     //Load Stripe Library
     require_once './vendor/stripe/stripe-php/lib/Stripe.php';
     if ($this->config->get('stripe_payments_mode') == 'live') {
         $stripe = array("secret_key" => $this->config->get('stripe_payments_private_key'), "publishable_key" => $this->config->get('stripe_payments_public_key'));
     } else {
         $stripe = array("secret_key" => $this->config->get('stripe_payments_private_key_test'), "publishable_key" => $this->config->get('stripe_payments_public_key_test'));
     }
     Stripe::setApiKey($stripe['secret_key']);
     $token = $_POST['stripeToken'];
     $error = null;
     try {
         $customer = Stripe_Customer::create(array('email' => $order_info['email'], 'card' => $token));
         $charge = Stripe_Charge::create(array('customer' => $customer->id, 'amount' => $amount, 'currency' => $order_info['currency_code'], 'metadata' => array('order_id' => $this->session->data['order_id'], 'customer' => $order_info['payment_firstname'] . ' ' . $order_info['payment_lastname'], 'email' => $order_info['email'], 'phone' => $order_info['telephone']), 'description' => 'Order ID# ' . $this->session->data['order_id']));
     } catch (Stripe_CardError $e) {
         // Error card processing
         $error = $e->jsonBody['error'];
     }
     //create object to use as json
     $json = array();
     //If successful log transaction in opencart system
     if (!$error) {
         $this->model_checkout_order->addOrderHistory($this->session->data['order_id'], $this->config->get('stripe_payments_order_status_id'));
         $json['success'] = $this->url->link('checkout/success', '', 'SSL');
     } else {
         $json['error'] = (string) $error['message'];
         $json['details'] = $error;
     }
     $this->response->setOutput(json_encode($json));
 }
예제 #5
0
 /**
  * Get a Stripe customer object instance.
  *
  * @param integer $user_id If it's for an existing user; pass the user's ID (optional).
  * @param string  $email Customer's email address (optional).
  * @param string  $fname Customer's first name (optional).
  * @param string  $lname Customer's last name (optional).
  * @param array   $metadata Any metadata (optional).
  *
  * @return Stripe_Customer|string Customer object; else error message.
  */
 public static function get_customer($user_id = 0, $email = '', $fname = '', $lname = '', $metadata = array())
 {
     $input_time = time();
     // Initialize.
     $input_vars = get_defined_vars();
     // Arguments.
     require_once dirname(__FILE__) . '/stripe-sdk/lib/Stripe.php';
     Stripe::setApiKey($GLOBALS['WS_PLUGIN__']['optimizemember']['o']['pro_stripe_api_secret_key']);
     try {
         try {
             if ($user_id && ($customer_id = get_user_option('optimizemember_subscr_cid', $user_id))) {
                 $customer = Stripe_Customer::retrieve($customer_id);
             }
         } catch (exception $exception) {
             // Fail silently; create a new customer below in this case.
         }
         if (empty($customer) || !is_object($customer)) {
             $customer = Stripe_Customer::create(array('email' => $email, 'description' => trim($fname . ' ' . $lname), 'metadata' => $metadata));
         }
         self::log_entry(__FUNCTION__, $input_time, $input_vars, time(), $customer);
         return $customer;
         // Stripe customer object.
     } catch (exception $exception) {
         self::log_entry(__FUNCTION__, $input_time, $input_vars, time(), $exception);
         return self::error_message($exception);
     }
 }
예제 #6
0
/**
 * Prepare stripe data for processing.
 */
function fwd_stripe_prepare($data, $settings)
{
    // Load stripe library?
    if (!class_exists('Stripe')) {
        require_once dirname(__FILE__) . '/stripe/lib/Stripe.php';
    }
    // Set API key.
    Stripe::setApiKey($settings['secret_key']);
    $order = get("/orders/{$data['order_id']}");
    $stripe = $order['billing']['stripe'];
    // Need to convert token to customer?
    if ($stripe['object'] == "token") {
        if ($stripe['used'] == 'true') {
            throw new Exception('Stripe token already used');
        }
        $customer = Stripe_Customer::create(array('description' => $order['billing']['name'], 'card' => $stripe['id']));
        $billing['stripe'] = $customer->__toArray(true);
        $billing['card'] = $billing['stripe']['active_card'];
        unset($billing['stripe']['active_card']);
        // Update order.
        put($order, array('billing' => $billing));
        // Update account billing also?
        if (($account_billing = $order['account']['billing']) && $account_billing['method'] == 'card' && $account_billing['stripe']['id'] == $stripe['id']) {
            $account_billing['stripe'] = $billing['stripe'];
            $account_billing['card'] = $billing['card'];
            put($order['account'], array('billing' => $account_billing));
        }
    }
    return $data;
}
예제 #7
0
 /**
  * @method POST
  */
 function pay()
 {
     // get token
     $token = Utilities::ValidateJWTToken(apache_request_headers());
     // check if token is not null
     if ($token != NULL) {
         // parse request
         parse_str($this->request->data, $request);
         $site = Site::GetBySiteId($token->SiteId);
         $siteId = $site['SiteId'];
         $email = $site['PrimaryEmail'];
         $status = 'Active';
         $stripe_token = $request['token'];
         $plan = $request['plan'];
         // set API key
         Stripe::setApiKey(STRIPE_SECRET_KEY);
         // create a new customer and subscribe them to the plan
         $customer = Stripe_Customer::create(array("card" => $stripe_token, "plan" => $plan, "email" => $email));
         // get back the id and the end period for the plan
         $id = $customer->id;
         // get subscription information
         $subscription = $customer->subscriptions->data[0];
         $subscriptionId = $subscription->id;
         $stripe_status = $subscription->status;
         $stripe_plan = $subscription->plan->id;
         $stripe_planname = $subscription->plan->name;
         // subscribe to a plan
         Site::Subscribe($siteId, $status, $plan, 'stripe', $subscriptionId, $customerId);
         // return a json response
         return new Tonic\Response(Tonic\Response::OK);
     } else {
         return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
     }
 }
예제 #8
0
 static function pay($currency)
 {
     global $wpdb, $user_ID, $user_email;
     $_course = new NamasteLMSCourseModel();
     $token = $_POST['stripeToken'];
     $course = get_post($_POST['course_id']);
     $fee = get_post_meta($course->ID, 'namaste_fee', true);
     $fee = apply_filters('namaste-coupon-applied', $fee);
     // coupon code from other plugin?
     try {
         $customer = Stripe_Customer::create(array('email' => $user_email, 'card' => $token));
         $charge = Stripe_Charge::create(array('customer' => $customer->id, 'amount' => $fee * 100, 'currency' => $currency));
     } catch (Exception $e) {
         wp_die($e->getMessage());
     }
     // !!!!in the next version avoid this copy-paste
     // almost the same code is in models/payment.php for the paypal payments
     $wpdb->query($wpdb->prepare("INSERT INTO " . NAMASTE_PAYMENTS . " SET \n\t\t\t\t\t\tcourse_id=%d, user_id=%s, date=CURDATE(), amount=%s, status='completed', paycode=%s, paytype='stripe'", $_POST['course_id'], $user_ID, $fee, $token));
     do_action('namaste-paid', $user_ID, $fee, "course", $_POST['course_id']);
     // enroll accordingly to course settings - this will be placed in a method once we
     // have more payment options
     $enroll_mode = get_post_meta($course->ID, 'namaste_enroll_mode', true);
     if (!NamasteLMSStudentModel::is_enrolled($user_ID, $course->ID)) {
         $status = $enroll_mode == 'free' ? 'enrolled' : 'pending';
         $_course->enroll($user_ID, $course->ID, $status);
     }
 }
예제 #9
0
 public function create()
 {
     if ($_POST) {
         $customer = Stripe_Customer::create(array('email' => $_POST['email']));
         foreach ($_POST as $key => $value) {
             $_POST[$key] = urldecode($value);
         }
         include OTHERS . "PasswordHash.php";
         $new_password = $_POST['password'];
         $salt = $this->_get_random_string(16);
         $hashed_password = create_hash($new_password . $salt);
         $stateSplit = explode(' - ', $_POST['state']);
         $key = $this->_get_random_string(50);
         $user = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname'], 'password' => $hashed_password, 'salt' => $salt, 'phone' => $_POST['phone'], 'email' => $_POST['email'], 'country' => $_POST['country'], 'state' => $stateSplit[1], 'state_abbr' => $stateSplit[0], 'confirmation_key' => $key, 'stripe_customer_id' => $customer->id);
         if (isset($_POST['reg_plan_id'])) {
             $user['stripe_reg_plan_id'] = $_POST['reg_plan_id'];
         } else {
             $this->load->model('settings_model');
             $general = transformArrayToKeyValue($this->settings_model->get(array('category' => 'general')));
             $this->load->model('package_model');
             $package = $this->package_model->getPackage($general['trial_period_package']->v);
             $user['stripe_reg_plan_id'] = $package->stripe_plan_id;
         }
         if ($this->user_model->add($user)) {
             echo "OK";
         }
     } else {
         $this->index();
     }
 }
예제 #10
0
 public function updatePlan(User $user, Plan $plan, $coupon_id = null)
 {
     $customer_id = $user->getProfile() ? $user->getProfile()->getCustomerId() : null;
     $new_plan_id = $plan->getId();
     if ($customer_id) {
         $customer = \Stripe_Customer::retrieve($customer_id);
         if ($coupon_id && $this->getCuponById($coupon_id)) {
             $customer->coupon = $coupon_id;
             $customer->save();
         }
         if ($new_plan_id !== 1) {
             $currentSubscription = $this->getCurrentSubscription($user, $customer);
             $subscription = $customer->subscriptions->retrieve($currentSubscription['id']);
             $subscription->plan = $new_plan_id;
             $proration_date = new \DateTime();
             $subscription->proration_date = $proration_date->getTimestamp();
             $subscription->tax_percent = 7;
             $subscription->save();
             $current_plan_id = $user->getCurrentPlan()->getPlan()->getId();
             if ($current_plan_id != 1) {
                 $invoice = \Stripe_Invoice::create(array("customer" => $customer_id, "subscription" => $subscription['id']));
                 $result = $invoice->pay();
                 if ($result->paid != true) {
                     $invoice->closed = true;
                     $invoice->save();
                     $customer->updateSubscription(array('plan' => $current_plan_id, 'prorate' => false, 'application_fee_percent' => 4, 'tax_percent' => 7));
                 }
             }
         }
     } else {
         //Inscribir al Usuario en el Plan Free por primera vez
         $customer = \Stripe_Customer::create(array("plan" => $new_plan_id, "email" => $user->getEmail()));
         $customer_id = $customer->id;
     }
     //Update Current Plan
     if (is_array($customer->subscriptions->data)) {
         foreach ($customer->subscriptions->data as $data) {
             if ($data->status == 'active') {
                 $dateStart = $data->current_period_start;
                 $dateEnd = $data->current_period_end;
                 break;
             }
         }
     } else {
         $dateStart = $customer->subscriptions->data->current_period_start;
         $dateEnd = $customer->subscriptions->data->current_period_end;
     }
     $dateTimeStart = new \DateTime();
     $dateTimeStart->setTimestamp($dateStart);
     $dateTimeEnd = new \DateTime();
     $dateTimeEnd->setTimestamp($dateEnd);
     $userPlan = new UserPlan($user, $plan);
     $userPlan->setDateStart($dateTimeStart);
     $userPlan->setDateEnd($dateTimeEnd);
     $user->getProfile()->setCustomerId($customer_id);
     $user->addPlan($userPlan);
     $this->saveData($user);
     return $plan;
 }
 public function testUpcoming()
 {
     authorizeFromEnv();
     $c = Stripe_Customer::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2015)));
     $invoice = Stripe_Invoice::upcoming(array('customer' => $c->id));
     $this->assertEqual($invoice->customer, $c->id);
     $this->assertEqual($invoice->attempted, false);
 }
 public function saveUserPayment()
 {
     $payment_token = Input::get('stripeToken');
     $owner_id = Session::get('user_id');
     $owner_data = Owner::find($owner_id);
     try {
         if (Config::get('app.default_payment') == 'stripe') {
             Stripe::setApiKey(Config::get('app.stripe_secret_key'));
             $customer = Stripe_Customer::create(array("card" => $payment_token, "description" => $owner_data->email));
             $last_four = substr(Input::get('number'), -4);
             if ($customer) {
                 $customer_id = $customer->id;
                 $payment = new Payment();
                 $payment->owner_id = $owner_id;
                 $payment->customer_id = $customer_id;
                 $payment->last_four = $last_four;
                 $payment->card_token = $customer->cards->data[0]->id;
                 $payment->save();
                 $message = "Your Card is successfully added.";
                 $type = "success";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             } else {
                 $message = "Sorry something went wrong.";
                 $type = "danger";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             }
         } else {
             Braintree_Configuration::environment(Config::get('app.braintree_environment'));
             Braintree_Configuration::merchantId(Config::get('app.braintree_merchant_id'));
             Braintree_Configuration::publicKey(Config::get('app.braintree_public_key'));
             Braintree_Configuration::privateKey(Config::get('app.braintree_private_key'));
             $result = Braintree_Customer::create(array("firstName" => $owner_data->first_name, "lastName" => $owner_data->last_name, "creditCard" => array("number" => Input::get('number'), "expirationMonth" => Input::get('month'), "expirationYear" => Input::get('year'), "cvv" => Input::get('cvv'))));
             Log::info('result = ' . print_r($result, true));
             if ($result->success) {
                 $num = $result->customer->creditCards[0]->maskedNumber;
                 $last_four = substr($num, -4);
                 $customer_id = $result->customer->id;
                 $payment = new Payment();
                 $payment->owner_id = $owner_id;
                 $payment->customer_id = $customer_id;
                 $payment->last_four = $last_four;
                 $payment->card_token = $result->customer->creditCards[0]->token;
                 $payment->save();
                 $message = "Your Card is successfully added.";
                 $type = "success";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             } else {
                 $message = "Sorry something went wrong.";
                 $type = "danger";
                 return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
             }
         }
     } catch (Exception $e) {
         $message = "Sorry something went wrong.";
         $type = "danger";
         return Redirect::to('/user/payments')->with('message', $message)->with('type', $type);
     }
 }
예제 #13
0
function stripeSubscribeCustomer()
{
    // 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::setApiKey("mDZRJuHrjeG3sSKJdmumEZdbGtr1TLDW");
    // get the credit card details submitted by the form
    $token = $_POST['stripeToken'];
    $customer = Stripe_Customer::create(array("card" => $token, "plan" => "gold", "email" => "*****@*****.**"));
}
예제 #14
0
 /**
  * Create a new customer
  * @param ElggUser $user
  * @param array $data
  * @return Stripe_Customer|false
  */
 public function createCustomer($user = null, $data = array())
 {
     $fields = array('account_balance', 'card', 'coupon', 'plan', 'quantity', 'trial_end', 'metadata', 'description', 'email');
     try {
         foreach ($data as $key => $value) {
             if (!in_array($key, $fields)) {
                 $data[$key] = '';
             }
         }
         $data = array_filter($data);
         if ($user) {
             if (!$data['email']) {
                 $data['email'] = $user->email;
             }
             if (!$data['description']) {
                 $data['description'] = $user->name;
             }
             if (!is_array($data['metadata'])) {
                 $data['metadata'] = array();
             }
             $data['metadata']['guid'] = $user->guid;
             $data['metadata']['username'] = $user->username;
         }
         $customer = Stripe_Customer::create($data);
         if ($user && $user->guid) {
             // Store any customer IDs this user might have for reference
             $stripe_ids = $user->stripe_customer_id;
             if (!$stripe_ids) {
                 $stripe_ids = array();
             } else {
                 if (!is_array($stripe_ids)) {
                     $stripe_ids = array($stripe_ids);
                 }
             }
             if (!in_array($customer->id, $stripe_ids)) {
                 create_metadata($user->guid, 'stripe_customer_id', $customer->id, '', $user->guid, ACCESS_PUBLIC, true);
             }
             // Store current Customer ID
             $user->setPrivateSetting('stripe_customer_id', $customer->id);
         } else {
             // Store customer IDs with their email reference locally
             // so that users can be assigned their existing customer ID upon registration
             $customer_ref = elgg_get_plugin_setting($customer->email, 'stripe');
             if ($customer_ref) {
                 $customer_ref = unserialize($customer_ref);
             } else {
                 $customer_ref = array();
             }
             array_unshift($customer_ref, $customer->id);
             elgg_set_plugin_setting($customer->email, serialize($customer_ref), 'stripe');
         }
         return $customer;
     } catch (Exception $ex) {
         $this->log($ex);
         return false;
     }
 }
 public function payForOrder($order)
 {
     // Create a new customer
     $customer = \Stripe_Customer::create(array('email' => $order['customerEmail'], 'card' => $order['token']));
     // Pay for order
     $charge = \Stripe_Charge::create(array('customer' => $customer->id, 'amount' => $order['price'] * 100, 'currency' => 'usd'));
     // Return charge object
     return array('chargeId' => $charge->id, 'customerId' => $customer->id);
 }
예제 #16
0
 public function testInvalidCredentials()
 {
     Stripe::setApiKey('invalid');
     try {
         Stripe_Customer::create();
     } catch (Stripe_AuthenticationError $e) {
         $this->assertEqual(401, $e->getHttpStatus());
     }
 }
예제 #17
0
 public function stripeAction(Request $request)
 {
     $em = $this->getDoctrine()->getEntityManager();
     $registerDetail = $em->createQueryBuilder()->select('SalonsolutionsUser')->from('SalonSolutionWebBundle:SalonsolutionsUser', 'SalonsolutionsUser')->addOrderBy('SalonsolutionsUser.id', 'DESC')->setMaxResults(1)->getQuery()->getResult();
     $userId = $registerDetail[0]->id;
     $firstName = $registerDetail[0]->firstName;
     $email = $registerDetail[0]->email;
     $em = $this->getDoctrine()->getEntityManager();
     $salonDetail = $em->createQueryBuilder()->select('SalonsolutionsSalon')->from('SalonSolutionWebBundle:SalonsolutionsSalon', 'SalonsolutionsSalon')->addOrderBy('SalonsolutionsSalon.id', 'DESC')->setMaxResults(1)->getQuery()->getResult();
     $salonId = $salonDetail[0]->id;
     $request = $this->container->get('request');
     $message = '';
     if ($request->get('test')) {
         Stripe::setApiKey('sk_test_ZPmfNFOUBUAY3YyiSSzUPMA8');
         $token = $request->get('stripeToken');
         $customer = \Stripe_Customer::create(array('email' => $email, 'card' => $token));
         $charge = \Stripe_Charge::create(array('customer' => $customer->id, 'amount' => 1000, 'currency' => 'usd', 'description' => $email));
         $customerId = $customer->id;
         $customeremail = $customer->email;
         $times = date_create();
         $time = date_format($times, 'H:i:s');
         $mydate = getdate(date("U"));
         $date = $mydate['weekday'] . ',' . $mydate['month'] . ',' . $mydate['mday'] . ',' . $mydate['year'];
         $message = 'Successfully Paid $10.00  !';
         $em = $this->getDoctrine()->getEntityManager();
         $confirmedPayment = $em->createQueryBuilder()->select('SalonsolutionsUser')->update('SalonSolutionWebBundle:SalonsolutionsUser', 'SalonsolutionsUser')->set('SalonsolutionsUser.status', ':status')->setParameter('status', '1')->where('SalonsolutionsUser.email = :email')->setParameter('email', $email)->getQuery()->getResult();
         $Payment = new SalonsolutionsPayment();
         $Payment->setUserId($userId);
         $Payment->setSalonId($salonId);
         $Payment->setTransactionId($customerId);
         $Payment->setTransactionDate($date);
         $Payment->setTransactionTime($time);
         $Payment->setTransactionAmount('10');
         $Payment->setPaymentMethodId('1');
         $em = $this->getDoctrine()->getEntityManager();
         $em->persist($Payment);
         $em->flush();
         $employeeMessage = new SalonsolutionsEmployeeMessages();
         $employeeMessage->setSalonOwnerId($userId);
         $employeeMessage->setType("Employee Message");
         $employeeMessage->setMessage("This is a message to be displayed on Employee Dashboard ");
         $employeeMessage->setStatus('0');
         $em = $this->getDoctrine()->getEntityManager();
         $em->persist($employeeMessage);
         $em->flush();
         $halfMessage = new SalonsolutionsEmployeeMessages();
         $halfMessage->setSalonOwnerId($userId);
         $halfMessage->setMessage("Offering Message");
         $halfMessage->setMessage("HALF PRICE SPRAY TANS EVERY FRIDAY !!! ");
         $halfMessage->setStatus('0');
         $em = $this->getDoctrine()->getEntityManager();
         $em->persist($halfMessage);
         $em->flush();
     }
     return $this->render('SalonSolutionWebBundle:Home:stripe.html.twig', array('message' => $message, 'firstName' => $firstName));
 }
예제 #18
0
 public function testCancelSubscription()
 {
     authorizeFromEnv();
     $c = Stripe_Customer::create(array('card' => array('number' => '4242424242424242', 'exp_month' => 5, 'exp_year' => 2015), 'plan' => 'gold'));
     $c->cancelSubscription(array('at_period_end' => true));
     $this->assertEqual($c->subscription->status, 'active');
     $this->assertTrue($c->subscription->cancel_at_period_end);
     $c->cancelSubscription();
     $this->assertEqual($c->subscription->status, 'canceled');
 }
예제 #19
0
 public function create_preapproval($params)
 {
     //error_log('Crowdfunding->create_preapproval params: '.print_r($params, true));
     include_once dirname(__FILE__) . '/aweber_api/aweber_api.php';
     date_default_timezone_set('America/Chicago');
     $db_params = parse_ini_file(dirname(dirname(__FILE__)) . '/configs/application.ini');
     $pdo = new PDO("mysql:dbname=" . $db_params['database.params.dbname'] . ";host=" . $db_params['database.params.host'], $db_params['database.params.username'], $db_params['database.params.password']);
     $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
     $pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
     $token = json_decode($params["cart_details"]["stripeToken"]);
     Stripe::setApiKey(STRIPE_SECRET_KEY);
     $customer = Stripe_Customer::create(array('email' => $token->email, 'card' => $token->id));
     //error_log('Crowdfunding->create_preapproval params: '.print_r($params, true));
     try {
         $sellingShare = $params['camp_details'][0]['selling_share'];
         if ($sellingShare <= 0) {
             $sellingShare = $params['camp_details'][0]['selling_price'] - $params['camp_details'][0]['base_price'];
             error_log('Crowdfunding->create_preapproval recover a selling share above 0 if possible: ' . $sellingShare);
         }
         $preApproveArray = array($params['camp_details'][0]['campaign_id'], $params['user'], $token->email, $params['cart_details']['cfname'] . ' ' . $params['cart_details']['clname'], $customer->id, $params['camp_details'][0]['selling_price'], $params['cart_details']['totquanty'] * $sellingShare, $params['cart_details']['total_Value_text'] - $params['cart_details']['totquanty'] * $sellingShare, $params['cart_details']['totquanty'], $params['sizes']);
         //error_log('Crowdfunding->create_preapproval inserted preapproval: '.print_r($preApproveArray, true));
         $preapproval = $pdo->prepare('INSERT INTO preapprovals VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, "created", "' . date("Y-m-d H:i:s", time()) . '")');
         $preapproval->execute($preApproveArray);
         $insert_id = $pdo->lastInsertId();
         //error_log('Crowdfunding->create_preapproval inserted preapproval has ID: '.$insert_id);
         $campaign_update = $pdo->prepare('UPDATE ' . LAUNCHCAMPAIGN . ' SET sold=sold+? WHERE campaign_id=?');
         $campaign_update->execute(array($params['cart_details']['totquanty'], $params['camp_details'][0]['campaign_id']));
         //error_log('Crowdfunding->create_preapproval update campaign ID '.$params['camp_details'][0]['campaign_id'].' with sold items increase with '.$params['cart_details']['totquanty'].' items');
     } catch (Exception $e) {
         error_log('Crowdfunding->create_preapproval exception: ' . $e->getMessage());
     }
     // Subscribe user to Aweber Client Mailing List
     /*
     $aweber = new AWeberAPI(AWEBER_KEY, AWEBER_SECRET);
     try {
         $account = $aweber->getAccount(AWEBER_ACCESS_KEY, AWEBER_ACCESS_SECRET);
     
         $listURL = "/accounts/" . AWEBER_ACCOUNT_ID . "/lists/" . AWEBER_CLIENTS_LIST_ID;
         $list = $account->loadFromUrl($listURL);
     
         $params = array(
             'email' => (string) $token->email,
             'ip_address' => $_SERVER["REMOTE_ADDR"],
             'ad_tracking' => $params["sizes"],
             'misc_notes' => money_format('$%i', $params['cart_details']['total_Value_text']),
             'name' => (string) $token->name
         );
         $subscribers = $list->subscribers;
     
         $new_subscriber = $subscribers->create($params);
     } catch (AWeberAPIException $e) {}
     */
     header("Location:" . APPLICATION_URL . $params['camp_details'][0]['url']);
 }
예제 #20
0
 public function indexAction()
 {
     $request = $this->container->get('request');
     $message = '';
     if ($request->get('test')) {
         \Stripe::setApiKey('pk_test_ur0ebwOGBrsNzQrpdCNENIu4');
         $token = $request->get('stripeToken');
         $customer = \Stripe_Customer::create(array('email' => '*****@*****.**', 'card' => $token));
         $charge = \Stripe_Charge::create(array('customer' => $customer->id, 'amount' => 5000, 'currency' => 'usd'));
         $message = '<h1>Successfully charged $50.00!</h1>';
     }
     return $this->render('AcmeTestBundle:Default:index.html.twig', array('message' => $message));
 }
 public function stripeAction()
 {
     $request = $this->container->get('request');
     $message = '';
     if ($request->get('test')) {
         \Stripe\Stripe::setApiKey('sk_test_ZPmfNFOUBUAY3YyiSSzUPMA8');
         $token = $request->get('stripeToken');
         $customer = \Stripe_Customer::create(array('email' => '*****@*****.**', 'card' => $token));
         $charge = \Stripe_Charge::create(array('customer' => $customer->id, 'amount' => 5000, 'currency' => 'usd'));
         $message = '<h1>Successfully charged $50.00!</h1>';
     }
     return $this->render('TestTestBundle:Page:stripe.html.twig', array('message' => $message));
 }
 /**
  * Create a Stripe customer
  */
 public function create($planId = false)
 {
     $user = $this->context->getToken()->getUser();
     if ($planId) {
         $customer = \Stripe_Customer::create(array("card" => $this->getToken(), "email" => $user->getEmail(), "plan" => $planId, "coupon" => $user->getCoupon()));
     } else {
         $customer = \Stripe_Customer::create(array("card" => $this->getToken(), "email" => $user->getEmail()));
     }
     $card = $customer->active_card;
     $user->setStripeCustomerId($customer->id);
     $user->setIsStripeCustomerActive(true);
     $user->setStripeCardReference(sprintf('%s - %s', $card->type, $card->last4));
     $this->userManager->updateUser($user);
     return true;
 }
예제 #23
0
 public function testSave()
 {
     $customer = self::createTestCustomer();
     $customer->email = '*****@*****.**';
     $customer->save();
     $this->assertEqual($customer->email, '*****@*****.**');
     $stripeCustomer = Stripe_Customer::retrieve($customer->id);
     $this->assertEqual($customer->email, $stripeCustomer->email);
     Stripe::setApiKey(null);
     $customer = Stripe_Customer::create(null, StripeTestCase::API_KEY);
     $customer->email = '*****@*****.**';
     $customer->save();
     StripeTestCase::authorizeFromEnv();
     $updatedCustomer = Stripe_Customer::retrieve($customer->id);
     $this->assertEqual($updatedCustomer->email, '*****@*****.**');
 }
예제 #24
0
 /**
  * {@inheritDoc}
  */
 public function execute($request)
 {
     /** @var $request CreateCharge */
     RequestNotSupportedException::assertSupports($this, $request);
     $model = ArrayObject::ensureArrayObject($request->getModel());
     $model->validateNotEmpty(array('plan'));
     if (false == $model['card']) {
         $this->gateway->execute(new ObtainToken($model));
     }
     try {
         \Stripe::setApiKey($this->keys->getSecretKey());
         $charge = \Stripe_Customer::create($model->toUnsafeArray());
         $model->replace($charge->__toArray(true));
     } catch (\Stripe_CardError $e) {
         $model->replace($e->getJsonBody());
     }
 }
예제 #25
0
 /**
  * Function to charge new customer on Stripe Sever
  * @param array $token
  * @param integer $name
  * @param string $user_id
  * @param mode Test or live mode
  */
 public function CreateCustomer($token, $name, $amount, $email = "", $description = "")
 {
     $this->setAPIKey();
     $customer = Stripe_Customer::create(array("card" => $token, "description" => $email));
     $input = array("amount" => $amount, "customer" => $customer->id, "currency" => "USD", "description" => $description);
     $result = Stripe_Charge::create($input);
     if ($result['paid'] === true) {
         /*
         			$result_array = array("success"=>"1","customer_id"=>$customer->id);	
         			return $result_array;
         */
         $result_array = array("success" => "1", "customer_id" => $customer->id, "response" => $result);
         return $result_array;
     } else {
         return $result;
     }
 }
 /**
  * Create a stripe customer
  *
  * @param string $planId
  */
 public function create($planId = false)
 {
     if ($planId) {
         $customer = \Stripe_Customer::create(array("card" => $this->getToken(), "email" => $this->user->getEmail(), "plan" => $planId));
         $plan = $this->planManager->find($planId);
         $this->user->setPlan($plan);
     } else {
         $customer = \Stripe_Customer::create(array("card" => $this->getToken(), "email" => $this->user->getEmail()));
     }
     $this->user->setStripeCustomerId($customer->id);
     $card = $customer->active_card;
     if ($card) {
         $this->user->setIsStripeCustomerActive(true);
         $this->user->setStripeCardReference(sprintf('%s - %s', $card->type, $card->last4));
     }
     $this->userManager->updateUser($this->user);
     return true;
 }
예제 #27
0
/**
 * Function that will actually charge the customers credit card
 *
 * @since 1.0.0
 */
function sc_charge_card()
{
    if (isset($_POST['stripeToken'])) {
        $redirect = $_POST['sc-redirect'];
        $fail_redirect = $_POST['sc-redirect-fail'];
        // 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'];
        $test_mode = isset($_POST['sc_test_mode']) ? $_POST['sc_test_mode'] : 'false';
        $charge = array();
        $query_args = array();
        $meta = array();
        $meta = apply_filters('sc_meta_values', $meta);
        sc_set_stripe_key($test_mode);
        // Create new customer
        $new_customer = Stripe_Customer::create(array('email' => $_POST['stripeEmail'], 'card' => $token));
        $amount = apply_filters('sc_charge_amount', $amount);
        // Create the charge on Stripe's servers - this will charge the user's default card
        try {
            $charge = Stripe_Charge::create(array('amount' => $amount, 'currency' => $currency, 'customer' => $new_customer['id'], 'description' => $description, 'metadata' => $meta));
            // Add Stripe charge ID to querystring.
            $query_args = array('charge' => $charge->id, 'store_name' => urlencode($store_name));
            $failed = false;
        } catch (Stripe_CardError $e) {
            // Catch Stripe errors
            $redirect = $fail_redirect;
            $e = $e->getJsonBody();
            // Add failure indicator to querystring.
            $query_args = array('charge' => $e['error']['charge'], 'charge_failed' => true);
            $failed = true;
        }
        unset($_POST['stripeToken']);
        do_action('sc_redirect_before');
        if ($test_mode == 'true') {
            $query_args['test_mode'] = 'true';
        }
        wp_redirect(add_query_arg($query_args, apply_filters('sc_redirect', $redirect, $failed)));
        do_action('sc_redirect_after');
        exit;
    }
}
 /**
  * boot
  *
  * @param Application $app
  */
 public function boot(Application $app)
 {
     if (empty($app['msiof.stripe']['keys']['secret'])) {
         throw new \RuntimeException('Stripe key not set msiof.stripe[keys][secret].  Cannot continue.');
     }
     if (empty($app['msiof.stripe']['keys']['publishable'])) {
         throw new \RuntimeException('Stripe key not set msiof.stripe[keys][publishable].  Cannot continue.');
     }
     \Stripe::setApiKey($app['msiof.stripe']['keys']['secret']);
     $app['dispatcher']->addListener(UserEvents::AFTER_INSERT, function (UserEvent $event) use($app) {
         $user = $event->getUser();
         $customer = \Stripe_Customer::create(['email' => $user->getEmail(), 'metadata' => ['userid' => $user->getId()]]);
         $subscription = $customer->subscriptions->create(["plan" => $app['msiof.stripe']['plans']['free']]);
         $user->setCustomField('stripe_customer_id', $customer->id);
         $user->setCustomField('stripe_subscription_id_free', $subscription->id);
         $user->setCustomField('stripe_current_plan', $app['msiof.stripe']['plans']['free']);
         $app['user.manager']->update($user);
     });
 }
예제 #29
0
 function post_customer($request_data)
 {
     // permission
     /*if(!$this->permission->check($request_data)) {
     			return $this->permission->errorMessage();
     		};*/
     /*// validation
     		$this->filter->set_request_data($request_data);
     		if(!$this->filter->run()) {
     			$return["errors"] = $this->filter->get_errors('error');
     			return $return;
     		}
     		$request_data = $this->filter->get_request_data();*/
     $request_data = $this->filter->run($request_data);
     if ($this->filter->hasErrors()) {
         return $this->filter->getErrorsReturn();
     }
     $c = Stripe_Customer::create(array("card" => $request_data['stripeToken'], "email" => USER_EMAIL));
     $this->db->insert_update('customers', array());
 }
예제 #30
0
 /**
  * @method POST
  */
 function post()
 {
     // parse request
     parse_str($this->request->data, $request);
     $token = $request['token'];
     $plan = $request['plan'];
     // get an authuser
     $authUser = new AuthUser();
     if (isset($authUser->UserUniqId)) {
         // check if authorized
         try {
             $site = Site::GetBySiteUniqId($authUser->SiteUniqId);
             if ($site['CustomerId'] == null) {
                 Stripe::setApiKey(STRIPE_API_KEY);
                 // create a new customer and subscribe them to the plan
                 $customer = Stripe_Customer::create(array("card" => $token, "plan" => $plan, "email" => $authUser->Email));
                 // get back the id and the end period for the plan
                 $customerId = $customer->id;
                 // #todo add customerid
                 Site::EditCustomer($site['SiteUniqId'], $customerId);
             } else {
                 Stripe::setApiKey(STRIPE_API_KEY);
                 $customer = Stripe_Customer::retrieve($site['CustomerId']);
                 $customer->updateSubscription(array("card" => $token, "plan" => $plan, "prorate" => true, "trial_end" => 'now'));
             }
             // return a json response
             return new Tonic\Response(Tonic\Response::OK);
         } catch (Exception $e) {
             $response = new Tonic\Response(Tonic\Response::BADREQUEST);
             $response->body = $e->getMessage();
             return $response;
         }
     } else {
         return new Tonic\Response(Tonic\Response::UNAUTHORIZED);
     }
 }