Fixed change card feature

This commit is contained in:
Levi 2017-01-20 11:33:25 -05:00
parent cb76fb4a1d
commit 63bb92fc6b
11 changed files with 268 additions and 871 deletions

View File

@ -0,0 +1,119 @@
$( document ).ready(function() {
var $form = $('#new-card-form');
$form.submit(changeCreditCard);
// var submit_form_btn = $('#change-card-button');
// submit_form_btn.on('click', submit_new_card);
function submit_new_card(e){
// $('#billing-form').submit();
// alert("POR AQUI2");
// $form.submit();
}
/* If you're using Stripe for payments */
function changeCreditCard(e) {
console.log("submiting");
e.preventDefault();
if (!$('.agree-terms').is(':checked')){
alert("You must accept terms and conditions.");
return;
}
/* Visual feedback */
$form.find('[type=submit]').html('Validating <i class="fa fa-spinner fa-pulse"></i>');
var PublishableKey = window.stripeKey;
Stripe.setPublishableKey(PublishableKey);
Stripe.card.createToken($form, function stripeResponseHandler(status, response) {
console.log("response",response);
if (response.error) {
/* Visual feedback */
alert("POR AQUI3");
$form.find('[type=submit]').html('Try again');
/* Show Stripe errors on the form */
$form.find('.payment-errors').text(response.error.message);
$form.find('.payment-errors').closest('.row').show();
} else {
/* Visual feedback */
$form.find('[type=submit]').html('Processing <i class="fa fa-spinner fa-pulse"></i>');
/* Hide Stripe errors on the form */
$form.find('.payment-errors').closest('.row').hide();
$form.find('.payment-errors').text("");
// response contains id and card, which contains additional card details
var token = response.id;
// AJAX
//set token on a hidden input
$('#id_token').val(token);
$('#change-card-form').submit();
}
});
}
/* Form validation */
$.validator.addMethod("month", function(value, element) {
return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value);
}, "Please specify a valid 2-digit month.");
$.validator.addMethod("year", function(value, element) {
return this.optional(element) || /^[0-9]{2}$/.test(value);
}, "Please specify a valid 2-digit year.");
validator = $form.validate({
rules: {
cardNumber: {
required: true,
creditcard: true,
digits: true
},
expMonth: {
required: true,
month: true
},
expYear: {
required: true,
year: true
},
cvCode: {
required: true,
digits: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
unhighlight: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
},
errorPlacement: function(error, element) {
$(element).closest('.form-group').append(error);
}
});
paymentFormReady = function() {
if ($form.find('[name=cardNumber]').hasClass("success") &&
$form.find('[name=expMonth]').hasClass("success") &&
$form.find('[name=expYear]').hasClass("success") &&
$form.find('[name=cvCode]').val().length > 1) {
return true;
} else {
return false;
}
};
$form.find('[type=submit]').prop('disabled', true);
var readyInterval = setInterval(function() {
if (paymentFormReady()) {
$form.find('[type=submit]').prop('disabled', false);
clearInterval(readyInterval);
}
}, 250);
});

View File

@ -28,10 +28,7 @@ $( document ).ready(function() {
var hasCreditcard = window.hasCreditcard; var hasCreditcard = window.hasCreditcard;
hasCreditcard= true; hasCreditcard= true;
console.log("has creditcard");
console.log("has creditcard");
console.log("has creditcard");
var submit_form_btn = $('#payment_button'); var submit_form_btn = $('#payment_button');
submit_form_btn.on('click', submit_payment); submit_form_btn.on('click', submit_payment);
@ -103,6 +100,7 @@ $( document ).ready(function() {
}); });
} }
/* Form validation */ /* Form validation */
$.validator.addMethod("month", function(value, element) { $.validator.addMethod("month", function(value, element) {
return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value); return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value);

View File

@ -76,7 +76,7 @@
</div> </div>
{% if credit_card_data.last4 %} {% if credit_card_data.last4 %}
<form role="form" id="billing-form" method="post" action="{% url 'digitalglarus:booking_payment' %}" novalidate> <form role="form" id="billing-form" method="post" action="{% url 'digitalglarus:booking_payment' %}" novalidate>
<h2 class="billing-head">Credit Card<a class="btn btn-primary btn-grey btn-edit" href="{% url 'digitalglarus:TermsAndConditions' %}">New</a></h2> <h2 class="billing-head">Credit Card<a class="btn btn-primary btn-grey btn-edit" href="{% url 'digitalglarus:edit_credit_card' %}">New</a></h2>
<h2 class="membership-lead">Last 4: *****{{credit_card_data.last4}}</h2> <h2 class="membership-lead">Last 4: *****{{credit_card_data.last4}}</h2>
<h2 class="membership-lead">Type: {{credit_card_data.cc_brand}}</h2> <h2 class="membership-lead">Type: {{credit_card_data.cc_brand}}</h2>
<input type="hidden" name="credit_card_needed" value="false"/> <input type="hidden" name="credit_card_needed" value="false"/>

View File

@ -30,34 +30,69 @@
<div class="signup-container"> <div class="signup-container">
<div class="col-xs-12 col-sm-6 col-lg-8 text-center wow fadeInDown"> <div class="col-xs-12 col-sm-6 col-lg-8 text-center wow fadeInDown">
<div class="payment-box"> <div class="payment-box">
<h2 class="section-heading payment-head">Edit Credit Card</h2> <h2 class="section-heading payment-head">New Credit Card</h2>
<!-- <h2 class="membership-amount">35CHF</h2> --> <!-- <h2 class="membership-amount">35CHF</h2> -->
<hr class="greyline-long"> <hr class="greyline-long">
<h2 class="membership-lead"> <h2 class="membership-lead">
</h2> </h2>
<br> <!-- {% if is_free %}
<h2 class="billing-head">Billing Adress</h2>
<div class="signup-form form-group row">
<form role="form" id="billing-form" method="post" action="{% url 'digitalglarus:booking_payment' %}" novalidate>
{% for field in form %}
{% csrf_token %}
{% bootstrap_field field show_label=False type='fields'%}
{% endfor %}
{% bootstrap_form_errors form type='non_fields'%}
<br>
</form>
</div>
<hr class="greyline-long">
<br/>
<h2 class="billing-head">Your booking is FREE of charge! You can change or cancel the booking freely 7 days before the booking date.</h2>
<br/><br/>
{% else %}
-->
<br>
<h2 class="billing-head">Credit Card Information</h2> <h2 class="billing-head">Credit Card Information</h2>
<form role="form" id="billing-form" method="post" action="{% url 'digitalglarus:booking_payment' %}" novalidate>
{% csrf_token %} <form role="form" id="change-card-form" method="post" action="{% url 'digitalglarus:edit_credit_card' %}" novalidate>
{% csrf_token %}
<h2 class="membership-lead">Last 4: *****{{last4}}</h2> <h2 class="membership-lead">Last 4: *****{{last4}}</h2>
<h2 class="membership-lead">Type: {{cc_brand}}</h2> <h2 class="membership-lead">Type: {{cc_brand}}</h2>
<h2 class="membership-lead">Exp month: {{expMonth}}</h2>
<h2 class="membership-lead">Exp year: {{expYear}}</h2>
<input type="hidden" name="credit_card_needed" value="false"/> <input type="hidden" name="credit_card_needed" value="false"/>
</form> <input type="hidden" name="token" id="id_token" value="false"/>
<h2 class="billing-head">Edit Card credit card</h2> </form>
<div class="signup-form form-group row"> <h2 class="billing-head">Credit Card (New One)</h2>
<div class="signup-form form-group row">
<!-- <form role="form" id="payment-form" novalidate> -->
<form role="form" id="payment-form2" method="post" action="{% url 'digitalglarus:booking_payment_view' %}" novalidate>
{% csrf_token %}
<div class="text-center">
<!-- <form role="form" id="payment-form" novalidate> -->
<form role="form" id="new-card-form" method="post" action="{% url 'digitalglarus:booking_payment' %}" novalidate>
{% csrf_token %}
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="form-group">
<input type="text" class="form-control" name="cardName" placeholder="Name on card" required autofocus data-stripe="name" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="form-group">
<input type="text" class="form-control" name="cardNumber" placeholder="Valid Card Number" required data-stripe="number" />
</div>
</div>
</div>
<div class="row"> <div class="row">
<div class="col-xs-12 col-md-6 nopadding"> <div class="col-xs-12 col-md-6 nopadding">
<label for="expMonth">EXPIRATION DATE</label><br/> <label for="expMonth">EXPIRATION DATE</label><br/>
@ -72,13 +107,27 @@
</div> </div>
</div> </div>
</div> </div>
<div class="col-xs-12 col-md-6 pull-right">
<div class="form-group">
<label for="cvCode">CV CODE</label>
<input type="password" class="form-control" name="cvCode" placeholder="CV" required data-stripe="cvc" />
</div>
</div>
</div> </div>
<input type="checkbox" hidden="True" class="custom-control-input agree-terms" checked> <input type="checkbox" hidden="True" class="custom-control-input agree-terms" checked>
<div class="row"> <div class="row">
<div class="col-xs-10 col-md-6 col-xs-offset-1 col-md-offset-3"> <div class="col-xs-10 col-md-6 col-xs-offset-1 col-md-offset-3">
<a class="btn btn-primary btn-grey" href="{% url 'digitalglarus:booking_payment' %}">Cancel</a>
<button class="btn btn-primary btn-md btn-blck submit-payment" type="submit">Save</button>
<a class="btn btn-primary btn-grey" href="{% url 'digitalglarus:booking_payment' %}">Cancel</a>
<button class="btn btn-primary btn-md btn-blck submit-payment" type="submit">Save</button>
</div> </div>
</div> </div>
<div class="row" style="display:none;"> <div class="row" style="display:none;">
<div class="col-xs-12"> <div class="col-xs-12">
@ -94,13 +143,12 @@
</div> </div>
</div> </div>
{% endif %} {% endif %}
</div>
</form> </form>
<br> <br>
</div>
</div>
<!-- {% endif %} -->
</div> </div>
</div> </div>
@ -135,159 +183,9 @@
{% if stripe_key %} {% if stripe_key %}
<script type="text/javascript"> <script type="text/javascript">
(function () {window.stripeKey = "{{stripe_key}}";})(); (function () {window.stripeKey = "{{stripe_key}}";})();
</script> </script>
{%endif%} {%endif%}
<script>
$( document ).ready(function() {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
alert("POR AQUI");
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
//Acept term and conditions button
var submit_form_btn = $('#payment_button');
submit_form_btn.on('click', submit_payment);
function submit_payment(e){
$('#billing-form').submit();
alert("POR AQUI2");
// $form.submit();
}
var $form = $('#payment-form');
$form.submit(payWithStripe);
/* If you're using Stripe for payments */
function payWithStripe(e) {
console.log("submiting");
e.preventDefault();
if (!$('.agree-terms').is(':checked')){
alert("You must accept terms and conditions.");
return;
}
/* Visual feedback */
$form.find('[type=submit]').html('Validating <i class="fa fa-spinner fa-pulse"></i>');
var PublishableKey = window.stripeKey;
Stripe.setPublishableKey(PublishableKey);
Stripe.card.createToken($form, function stripeResponseHandler(status, response) {
if (response.error) {
/* Visual feedback */
alert("POR AQUI3");
$form.find('[type=submit]').html('Try again');
/* Show Stripe errors on the form */
$form.find('.payment-errors').text(response.error.message);
$form.find('.payment-errors').closest('.row').show();
} else {
/* Visual feedback */
$form.find('[type=submit]').html('Processing <i class="fa fa-spinner fa-pulse"></i>');
/* Hide Stripe errors on the form */
$form.find('.payment-errors').closest('.row').hide();
$form.find('.payment-errors').text("");
// response contains id and card, which contains additional card details
var token = response.id;
// AJAX
//set token on a hidden input
$('#id_token').val(token);
$('#billing-form').submit();
}
});
}
/* Form validation */
$.validator.addMethod("month", function(value, element) {
return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value);
}, "Please specify a valid 2-digit month.");
$.validator.addMethod("year", function(value, element) {
return this.optional(element) || /^[0-9]{2}$/.test(value);
}, "Please specify a valid 2-digit year.");
validator = $form.validate({
rules: {
cardNumber: {
required: true,
creditcard: true,
digits: true
},
expMonth: {
required: true,
month: true
},
expYear: {
required: true,
year: true
},
cvCode: {
required: true,
digits: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
unhighlight: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
},
errorPlacement: function(error, element) {
$(element).closest('.form-group').append(error);
}
});
paymentFormReady = function() {
if ($form.find('[name=cardNumber]').hasClass("success") &&
$form.find('[name=expMonth]').hasClass("success") &&
$form.find('[name=expYear]').hasClass("success") &&
$form.find('[name=cvCode]').val().length > 1) {
return true;
} else {
return false;
}
};
$form.find('[type=submit]').prop('disabled', true);
var readyInterval = setInterval(function() {
if (paymentFormReady()) {
$form.find('[type=submit]').prop('disabled', false);
clearInterval(readyInterval);
}
}, 250);
});
</script>
{% endblock %} {% endblock %}

View File

@ -1,106 +0,0 @@
{% extends "new_base_glarus.html" %}
{% load staticfiles cms_tags bootstrap3%}
{% block title %}crowdfunding{% endblock %}
{% block content %}
<style type="text/css">
#cancel-subscription-modal{
margin-top:10%;
}
#cancel-subscription-modal .modal-header{
border-bottom: none;
}
#cancel-subscription-modal .modal-footer{
border-top: none;
text-align: center;
}
</style>
<section id="price">
<div class="signup-container">
<div class="col-xs-12 col-sm-3 col-lg-4 text-center wow fadeInDown"> </div>
<div class="col-xs-12 col-sm-6 col-lg-4 text-center wow fadeInDown">
<!-- <span class="glyphicon glyphicon-user"></span> -->
<div class="payment-box">
<h2 class="billing-head">Membership Deactivation</h2>
<hr class="greyline-long">
<h2 class="membership-lead">Do you want to cancel your membership with us ?</h2>
<div class="date-box">
</div>
<!--<hr class="primary">-->
<div class="signup-form form-group row">
<div class="button-booking-box form-inline row">
<form method="POST" action="">
{% csrf_token %}
<button type="button" class="btn btn-primary btn-blue" data-toggle="modal" data-target="#cancel-subscription-modal">Cancel my Membership</button>
<a class="btn btn-primary btn-blue" href="{{request.META.HTTP_REFERER}}">Go back</a>
<div class="modal fade bs-example-modal-sm" id="cancel-subscription-modal" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
<h4 class="modal-title">Cancel Subscription</h4>
</div>
<div class="modal-body">
<p>Do you want to cancel your subscription?</p>
</div>
<div class="modal-footer text-center">
<button type="button" class="btn btn-primary btn-grey" data-dismiss="modal">No</button>
<button type="submit" class="btn btn-primary">Yes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
</form>
</div>
<div class="notice-box text-left">
<p class="order-bottom-text">
Your membership wouldn't be automatically renewed each month.
</p>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-3 col-lg-4 text-center wow fadeInDown"> </div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="contact">
<div class="fill">
<div class="row" class="wow fadeInDown">
<div class="col-lg-12 text-center wow fadeInDown">
<div class="col-md-4 map-title">
Digital Glarus<br>
<span class="map-caption">In der Au 7 Schwanden 8762 Switzerland
<br>info@digitalglarus.ch
<br>
(044) 534-66-22
<p>&nbsp;</p>
</span>
</div>
<p>&nbsp;</p>
</div>
</div>
</div>
</section>
{% endblock %}

View File

@ -1,340 +0,0 @@
{% extends "new_base_glarus.html" %}
{% load staticfiles bootstrap3 i18n %}
{% block content %}
<style type="text/css">
.nopadding {
padding: 0 !important;
margin: 0 !important;
}
.form-control#id_country{
-webkit-appearance: none;
-moz-appearance: none;
background-position: right 50%;
background-repeat: no-repeat;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAMCAYAAABSgIzaAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyJpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuMC1jMDYwIDYxLjEzNDc3NywgMjAxMC8wMi8xMi0xNzozMjowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENTNSBNYWNpbnRvc2giIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6NDZFNDEwNjlGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6NDZFNDEwNkFGNzFEMTFFMkJEQ0VDRTM1N0RCMzMyMkIiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDo0NkU0MTA2N0Y3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDo0NkU0MTA2OEY3MUQxMUUyQkRDRUNFMzU3REIzMzIyQiIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/PuGsgwQAAAA5SURBVHjaYvz//z8DOYCJgUxAf42MQIzTk0D/M+KzkRGPoQSdykiKJrBGpOhgJFYTWNEIiEeAAAMAzNENEOH+do8AAAAASUVORK5CYII=);
padding: .5em;
padding-right: 1.5em
}
.order-bottom-text a{
margin-left: 0px;
}
</style>
<section id="price">
<div class="signup-container">
<div class="col-xs-12 col-sm-6 col-lg-8 text-center wow fadeInDown">
<div class="payment-box">
<h2 class="section-heading payment-head">New Credit Card</h2>
<!-- <h2 class="membership-amount">35CHF</h2> -->
<hr class="greyline-long">
<h2 class="membership-lead">
</h2>
<!-- {% if is_free %}
<h2 class="billing-head">Billing Adress</h2>
<div class="signup-form form-group row">
<form role="form" id="billing-form" method="post" action="{% url 'digitalglarus:booking_payment' %}" novalidate>
{% for field in form %}
{% csrf_token %}
{% bootstrap_field field show_label=False type='fields'%}
{% endfor %}
{% bootstrap_form_errors form type='non_fields'%}
<br>
</form>
</div>
<hr class="greyline-long">
<br/>
<h2 class="billing-head">Your booking is FREE of charge! You can change or cancel the booking freely 7 days before the booking date.</h2>
<br/><br/>
{% else %}
-->
<br>
<h2 class="billing-head">Credit Card Information</h2>
<form role="form" id="billing-form" method="post" action="{% url 'digitalglarus:booking_payment' %}" novalidate>
{% csrf_token %}
<h2 class="membership-lead">Last 4: *****{{last4}}</h2>
<h2 class="membership-lead">Type: {{cc_brand}}</h2>
<input type="hidden" name="credit_card_needed" value="false"/>
</form>
<h2 class="billing-head">Credit Card (New One)</h2>
<div class="signup-form form-group row">
<!-- <form role="form" id="payment-form" novalidate> -->
<form role="form" id="payment-form2" method="post" action="{% url 'digitalglarus:booking_payment_view' %}" novalidate>
{% csrf_token %}
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="form-group">
<input type="text" class="form-control" name="cardName" placeholder="Name on card" required autofocus data-stripe="name" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="form-group">
<input type="text" class="form-control" name="cardNumber" placeholder="Valid Card Number" required data-stripe="number" />
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-md-6 nopadding">
<label for="expMonth">EXPIRATION DATE</label><br/>
<div class="col-xs-6 col-lg-6 col-md-6">
<div class="form-group">
<input type="text" class="form-control" name="expMonth" placeholder="MM" required data-stripe="exp_month" />
</div>
</div>
<div class="col-xs-6 col-lg-6 col-md-6 pl-ziro">
<div class="form-group">
<input type="text" class="form-control" name="expYear" placeholder="YY" required data-stripe="exp_year" />
</div>
</div>
</div>
<div class="col-xs-12 col-md-6 pull-right">
<div class="form-group">
<label for="cvCode">CV CODE</label>
<input type="password" class="form-control" name="cvCode" placeholder="CV" required data-stripe="cvc" />
</div>
</div>
</div>
<input type="checkbox" hidden="True" class="custom-control-input agree-terms" checked>
<div class="row">
<div class="col-xs-10 col-md-6 col-xs-offset-1 col-md-offset-3">
<a class="btn btn-primary btn-grey" href="{% url 'digitalglarus:booking_payment' %}">Cancel</a>
<button class="btn btn-primary btn-md btn-blck submit-payment" type="submit">Save</button>
</div>
</div>
<div class="row" style="display:none;">
<div class="col-xs-12">
<p class="payment-errors"></p>
</div>
</div>
{% if paymentError %}
<div class="row">
<div class="col-xs-12">
<p>
{% bootstrap_alert paymentError alert_type='danger' %}
</p>
</div>
</div>
{% endif %}
</form>
<br>
</div>
<!-- {% endif %} -->
</div>
</div>
</div>
</div>
</div>
</div>
</section>
<section id="contact">
<div class="fill">
<div class="row" class="wow fadeInDown">
<div class="col-lg-12 text-center wow fadeInDown">
<div class="col-md-4 map-title">
Digital Glarus<br>
<span class="map-caption">In der Au 7 Schwanden 8762 Switzerland
<br>info@digitalglarus.ch
<br>
(044) 534-66-22
<p>&nbsp;</p>
</span>
</div>
<p>&nbsp;</p>
</div>
</div>
</div>
</section>
<!-- stripe key data -->
{% if stripe_key %}
<script type="text/javascript">
(function () {window.stripeKey = "{{stripe_key}}";})();
</script>
{%endif%}
<script>
$( document ).ready(function() {
$.ajaxSetup({
beforeSend: function(xhr, settings) {
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
alert("POR AQUI");
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
//Acept term and conditions button
var submit_form_btn = $('#payment_button');
submit_form_btn.on('click', submit_payment);
function submit_payment(e){
$('#billing-form').submit();
alert("POR AQUI2");
// $form.submit();
}
var $form = $('#payment-form');
$form.submit(payWithStripe);
/* If you're using Stripe for payments */
function payWithStripe(e) {
console.log("submiting");
e.preventDefault();
if (!$('.agree-terms').is(':checked')){
alert("You must accept terms and conditions.");
return;
}
/* Visual feedback */
$form.find('[type=submit]').html('Validating <i class="fa fa-spinner fa-pulse"></i>');
var PublishableKey = window.stripeKey;
Stripe.setPublishableKey(PublishableKey);
Stripe.card.createToken($form, function stripeResponseHandler(status, response) {
if (response.error) {
/* Visual feedback */
alert("POR AQUI3");
$form.find('[type=submit]').html('Try again');
/* Show Stripe errors on the form */
$form.find('.payment-errors').text(response.error.message);
$form.find('.payment-errors').closest('.row').show();
} else {
/* Visual feedback */
$form.find('[type=submit]').html('Processing <i class="fa fa-spinner fa-pulse"></i>');
/* Hide Stripe errors on the form */
$form.find('.payment-errors').closest('.row').hide();
$form.find('.payment-errors').text("");
// response contains id and card, which contains additional card details
var token = response.id;
// AJAX
//set token on a hidden input
$('#id_token').val(token);
$('#billing-form').submit();
}
});
}
/* Form validation */
$.validator.addMethod("month", function(value, element) {
return this.optional(element) || /^(01|02|03|04|05|06|07|08|09|10|11|12)$/.test(value);
}, "Please specify a valid 2-digit month.");
$.validator.addMethod("year", function(value, element) {
return this.optional(element) || /^[0-9]{2}$/.test(value);
}, "Please specify a valid 2-digit year.");
validator = $form.validate({
rules: {
cardNumber: {
required: true,
creditcard: true,
digits: true
},
expMonth: {
required: true,
month: true
},
expYear: {
required: true,
year: true
},
cvCode: {
required: true,
digits: true
}
},
highlight: function(element) {
$(element).closest('.form-control').removeClass('success').addClass('error');
},
unhighlight: function(element) {
$(element).closest('.form-control').removeClass('error').addClass('success');
},
errorPlacement: function(error, element) {
$(element).closest('.form-group').append(error);
}
});
paymentFormReady = function() {
if ($form.find('[name=cardNumber]').hasClass("success") &&
$form.find('[name=expMonth]').hasClass("success") &&
$form.find('[name=expYear]').hasClass("success") &&
$form.find('[name=cvCode]').val().length > 1) {
return true;
} else {
return false;
}
};
$form.find('[type=submit]').prop('disabled', true);
var readyInterval = setInterval(function() {
if (paymentFormReady()) {
$form.find('[type=submit]').prop('disabled', false);
clearInterval(readyInterval);
}
}, 250);
});
</script>
{% endblock %}

View File

@ -281,11 +281,12 @@
<script src="{% static 'digitalglarus/js/agency.js' %}"></script> <script src="{% static 'digitalglarus/js/agency.js' %}"></script>
<script src="{% static 'digitalglarus/js/ungleich.js' %}"></script> <script src="{% static 'digitalglarus/js/ungleich.js' %}"></script>
<script src="{% static 'digitalglarus/js/edit_creditcard.js' %}"></script>
<!-- Include Required Prerequisites --> <!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script> <!-- <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script> -->
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script> <script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css" /> <!-- <link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/latest/css/bootstrap.css" />
--> -->

View File

@ -2,25 +2,20 @@ from django.conf.urls import url
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from . import views from . import views
from .views import ContactView, IndexView, AboutView, HistoryView, LoginView, SignupView,\ from .views import ContactView, IndexView, HistoryView, LoginView, SignupView,\
PasswordResetView, PasswordResetConfirmView, MembershipPaymentView, MembershipActivatedView,\ PasswordResetView, PasswordResetConfirmView, MembershipPaymentView, MembershipActivatedView,\
MembershipPricingView, BookingSelectDatesView, BookingPaymentView, OrdersBookingDetailView,\ MembershipPricingView, BookingSelectDatesView, BookingPaymentView, OrdersBookingDetailView,\
BookingOrdersListView, MembershipOrdersListView, OrdersMembershipDetailView, \ BookingOrdersListView, MembershipOrdersListView, OrdersMembershipDetailView, \
MembershipDeactivateView, MembershipDeactivateSuccessView, UserBillingAddressView,EditCreditCard, \ MembershipDeactivateView, MembershipDeactivateSuccessView, UserBillingAddressView, EditCreditCardView, \
MembershipReactivateView,TermsAndConditions,ValidateUser,SupportusView,Probar,TermsAndConditions2,TermsAndConditions3,BookingPaymentView2 MembershipReactivateView, SupportusView
# from membership.views import LoginRegistrationView # from membership.views import LoginRegistrationView
urlpatterns = [ urlpatterns = [
url(_(r'booking/payment/edit/?$'),EditCreditCard,name= 'edit_credit_card'), url(_(r'booking/payment/edit/?$'), EditCreditCardView.as_view(), name='edit_credit_card'),
url(_(r'booking/payment/view/?$'), BookingPaymentView2, name='booking_payment_view'),
url(_(r'probar3/?$'),TermsAndConditions3, name='probar3'),
url(_(r'probar2/?$'),TermsAndConditions2.as_view(), name='credit_card_edit'),
url(_(r'probar/?$'), Probar, name='probar'),
url(_(r'login/validate/(?P<pk>\!\w+)/?$'), ValidateUser.as_view(), name='validate-login'),
url(_(r'^$'), IndexView.as_view(), name='landing'), url(_(r'^$'), IndexView.as_view(), name='landing'),
url(_(r'new_credit_card/?$'), TermsAndConditions, name='TermsAndConditions'), # url(_(r'new_credit_card/?$'), TermsAndConditions, name='TermsAndConditions'),
url(_(r'support-us/?$'), SupportusView.as_view(), name='supportus'), url(_(r'support-us/?$'), SupportusView.as_view(), name='supportus'),
url(_(r'contact/?$'), ContactView.as_view(), name='contact'), url(_(r'contact/?$'), ContactView.as_view(), name='contact'),
url(_(r'login/?$'), LoginView.as_view(), name='login'), url(_(r'login/?$'), LoginView.as_view(), name='login'),
@ -57,8 +52,6 @@ urlpatterns = [
url(_(r'membership/orders/?$'), MembershipOrdersListView.as_view(), url(_(r'membership/orders/?$'), MembershipOrdersListView.as_view(),
name='membership_orders_list'), name='membership_orders_list'),
url(_(r'supporters/?$'), views.supporters, name='supporters'), url(_(r'supporters/?$'), views.supporters, name='supporters'),
url(r'calendar_api/(?P<month>\d+)/(?P<year>\d+)?$', views.CalendarApi.as_view(),name='calendar_api_1'),
url(r'calendar_api/', views.CalendarApi.as_view(),name='calendar_api'),
# url(_(r'support-us/?$'), views.support, name='support'), # url(_(r'support-us/?$'), views.support, name='support'),
url(r'^blog/(?P<slug>\w[-\w]*)/$', views.blog_detail, name='blog-detail'), url(r'^blog/(?P<slug>\w[-\w]*)/$', views.blog_detail, name='blog-detail'),
url(r'blog/$', views.blog, name='blog'), url(r'blog/$', views.blog, name='blog'),

View File

@ -1,10 +1,5 @@
import json
import datetime
from django.views.decorators.csrf import csrf_protect, csrf_exempt
from django.template import RequestContext
from django.conf import settings from django.conf import settings
from django.shortcuts import get_object_or_404, render from django.shortcuts import render
from django.forms import ModelForm
from django.http import HttpResponseRedirect from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse_lazy, reverse from django.core.urlresolvers import reverse_lazy, reverse
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
@ -13,23 +8,18 @@ from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.translation import get_language from django.utils.translation import get_language
from djangocms_blog.models import Post from djangocms_blog.models import Post
from django.contrib import messages from django.contrib import messages
from django.http import JsonResponse from django.views.generic import DetailView, ListView
from django.views.generic import View, DetailView, ListView, DeleteView
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response, redirect, render
from .models import Supporter from .models import Supporter
from .mixins import ChangeMembershipStatusMixin from .mixins import ChangeMembershipStatusMixin
from utils.forms import ContactUsForm from utils.forms import ContactUsForm
from utils.mailer import BaseEmail from utils.mailer import BaseEmail
from django.views.generic.edit import FormView from django.views.generic.edit import FormView
from membership.calendar.calendar import BookCalendar from membership.models import StripeCustomer
from membership.models import Calendar as CalendarModel, StripeCustomer
from utils.views import LoginViewMixin, SignupViewMixin, \ from utils.views import LoginViewMixin, SignupViewMixin, \
PasswordResetViewMixin, PasswordResetConfirmViewMixin PasswordResetViewMixin, PasswordResetConfirmViewMixin
from utils.forms import PasswordResetRequestForm, UserBillingAddressForm from utils.forms import PasswordResetRequestForm, UserBillingAddressForm, EditCreditCardForm
from utils.stripe_utils import StripeUtils from utils.stripe_utils import StripeUtils
from utils.models import UserBillingAddress from utils.models import UserBillingAddress
import stripe
from .forms import LoginForm, SignupForm, MembershipBillingForm, BookingDateForm,\ from .forms import LoginForm, SignupForm, MembershipBillingForm, BookingDateForm,\
BookingBillingForm, CancelBookingForm BookingBillingForm, CancelBookingForm
@ -38,142 +28,6 @@ from .models import MembershipType, Membership, MembershipOrder, Booking, Bookin
BookingOrder, BookingCancellation BookingOrder, BookingCancellation
from .mixins import MembershipRequiredMixin, IsNotMemberMixin from .mixins import MembershipRequiredMixin, IsNotMemberMixin
def BookingPaymentView2(request):
#print (request.user)
resp = dict()
cus = StripeCustomer.get_or_create(email=request.user.email)
s= str(cus)
s= s.split(" ")
resp['object']='card'
resp['exp_month']=request.POST['expMonth']
resp['exp_year']=request.POST['expYear']
resp['number']=request.POST['cardNumber']
resp['cvc']=request.POST['cvCode']
resp['name']=request.POST['cardName']
customer = stripe.Customer.retrieve(s[0])
customer.sources.create(source=resp)
t=stripe.Customer.retrieve(s[0]).sources.all(object="card")
tt=t['data']
x= resp['number']
cc= dict()
for i in tt:
#print (i.id)
#print (i.last4)
#print (x[-4:])
if i.last4 == x[-4:]:
cc['last4']= i.last4
cc['cc_brand']= i.brand
customer.default_source= i.id
customer.save()
current_billing_address = request.user.billing_addresses.first()
#return HttpResponse(json.dumps(resp), content_type ='application/json')
#return render_to_response('digitalglarus/booking_payment.html',{'last4':cc['last4'],'stripe_key': settings.STRIPE_API_PUBLIC_KEY,'street_address': current_billing_address.street_address,'city': current_billing_address.city, 'postal_code': current_billing_address.postal_code,'country': current_billing_address.country,},context_instance= RequestContext(request))
return HttpResponseRedirect('/digitalglarus/booking/payment/')
def Probar(TemplateView):
print ("hello")
class ValidateUser(TemplateView):
#print ("ENTRE AQUI AL MENOS Y",pk)
template_name = "digitalglarus/signup.html"
#form_class = SignupForm
success_url = reverse_lazy('digitalglarus:login')
#if request.method == 'POST':
#u = U.objects.get(pk = pk)
#u.is_active = True
#u.save()
#messages.info(request, 'Usuario Activado')
#Log('activar','usuario',request)
#resp = dict()
#resp['msg'] = 0 #0 para exito
#return HttpResponse(json.dumps(resp), content_type ='application/json')
class ValidateView(SignupViewMixin):
template_name = "digitalglarus/signup.html"
form_class = SignupForm
success_url = reverse_lazy('digitalglarus:login')
@csrf_exempt
def TermsAndConditions(request):
cus = StripeCustomer.get_or_create(email=request.user.email)
s= str(cus)
s= s.split(" ")
cc = dict()
customer = stripe.Customer.retrieve(s[0])
custom_card= customer.default_source
card = customer.sources.retrieve(custom_card)
cc['last4']= card.last4
cc['cc_brand'] = card.brand
m=MembershipOrder.objects.filter(customer__user=request.user)
#customer = StripeCustomer.get_or_create(email=request.user.email)
last_booking_order = BookingOrder.objects.filter(customer__user=request.user).last()
last_membership_order = MembershipOrder.objects.filter(customer__user=request.user).last()
current_billing_address = request.user.billing_addresses.first()
return render_to_response('digitalglarus/new_credit_card.html',{'last4':cc['last4'],'brand_type':cc['cc_brand'],'stripe_key': settings.STRIPE_API_PUBLIC_KEY,'street_address': current_billing_address.street_address,'city': current_billing_address.city, 'postal_code': current_billing_address.postal_code,'country': current_billing_address.country,},context_instance= RequestContext(request))
def TermsAndConditions3(request):
return render_to_response('digitalglarus/new_credit_card.html',{'last4':credit_card_data['last4'],'brand_type':credit_card_data['cc_brand']})
def EditCreditCard(request):
cus = StripeCustomer.get_or_create(email=request.user.email)
s= str(cus)
s= s.split(" ")
#t=stripe.Customer.retrieve(s[0]).sources.all(object="card")
#tt=t['data']
#print (tt)
#for i in tt:
# print (i.id)
# print (i.last4)
# print ("aja estoy aqui",i.id)
# customer = stripe.Customer.retrieve(s[0])
# customer.sources.retrieve(i.id).delete()
# crear tarjeta de credito
customer = stripe.Customer.retrieve(s[0])
#print ("voy por aqui")
custom_card= customer.default_source
t=stripe.Customer.retrieve(s[0]).sources.all(object="card")
tt=t['data']
#print (tt)
cc = dict()
for i in tt:
#print (i.id)
#print (i.last4)
if i.id== custom_card:
#print ("ESTA ES LA TARJETA ACTUAL")
cc['last4']= i.last4
cc['cc_brand'] = i.brand
cc['exp_month']=i.exp_month
cc['exp_year']= i.exp_year
#customer.sources.create(source=resp)
#t=stripe.Customer.retrieve(s[0]).sources.all(object="card")
#tt=t['data']
#x= resp['number']
#for i in tt:
# print (i.id)
# print (i.last4)
# print (x[-4:])
# if i.last4 == x[-4:]:
# print ("ESTOY AQUI")
# customer.default_source= i.id
#customer.save()
m=MembershipOrder.objects.filter(customer__user=request.user)
customer = StripeCustomer.get_or_create(email=request.user.email)
last_booking_order = BookingOrder.objects.filter(customer__user=request.user).last()
last_membership_order = MembershipOrder.objects.filter(customer__user=request.user).last()
credit_card_data = last_booking_order.get_booking_cc_data() if last_booking_order \
and last_booking_order.get_booking_cc_data() \
else last_membership_order.get_membership_order_cc_data()
current_billing_address = request.user.billing_addresses.first()
return render_to_response('digitalglarus/edit_credit_card.html',{'last4':cc['last4'],'brand_type':cc['cc_brand'],'expMonth': cc['exp_month'], 'expYear': cc['exp_year']})
class TermsAndConditions2(TemplateView):
template_name ="digitalglarus/credit_card_edit_confirmation.html"
class IndexView(TemplateView): class IndexView(TemplateView):
@ -237,6 +91,32 @@ class HistoryView(TemplateView):
return context return context
class EditCreditCardView(FormView):
template_name = "digitalglarus/edit_credit_card.html"
form_class = EditCreditCardForm
success_url = reverse_lazy('digitalglarus:booking_payment')
def get_context_data(self, *args, **kwargs):
context = super(EditCreditCardView, self).get_context_data(*args, **kwargs)
context.update({
'stripe_key': settings.STRIPE_API_PUBLIC_KEY
})
return context
def form_valid(self, form):
token = form.cleaned_data.get('token')
user = self.request.user
customer = user.stripecustomer
stripe_utls = StripeUtils()
card_response = stripe_utls.update_customer_card(customer.stripe_id, token)
new_card_data = card_response.get('response_object')
self.request.session.update({
'new_change_credit_card': new_card_data
})
return super(EditCreditCardView, self).form_valid(form)
class BookingSelectDatesView(LoginRequiredMixin, MembershipRequiredMixin, FormView): class BookingSelectDatesView(LoginRequiredMixin, MembershipRequiredMixin, FormView):
template_name = "digitalglarus/booking.html" template_name = "digitalglarus/booking.html"
form_class = BookingDateForm form_class = BookingDateForm
@ -320,34 +200,16 @@ class BookingPaymentView(LoginRequiredMixin, MembershipRequiredMixin, FormView):
user = self.request.user user = self.request.user
last_booking_order = BookingOrder.objects.filter(customer__user=user).last() last_booking_order = BookingOrder.objects.filter(customer__user=user).last()
last_membership_order = MembershipOrder.objects.filter(customer__user=user).last() last_membership_order = MembershipOrder.objects.filter(customer__user=user).last()
#credit_card_data = last_booking_order.get_booking_cc_data() if last_booking_order \ # check if user changes his credit card
# and last_booking_order.get_booking_cc_data() \ credit_card_data = self.request.session.get('new_change_credit_card')
# else last_membership_order.get_membership_order_cc_data() # import pdb
#print ("LA TARJETA NATACHA QUE QUEREMOS VER SI FUNCIONA ES ESTA",credit_card_data) # pdb.set_trace()
#credit_card_data =
#### ESTOY POR AQUI CAMBIANDO ESTO UN POCO PARA VER SI FUNCIONA if not credit_card_data:
########################################################################################## credit_card_data = last_booking_order.get_booking_cc_data() if last_booking_order \
cus = StripeCustomer.get_or_create(email=user) and last_booking_order.get_booking_cc_data() \
s= str(cus) else last_membership_order.get_membership_order_cc_data()
s= s.split(" ")
customer = stripe.Customer.retrieve(s[0])
#print ("voy por aqui")
custom_card= customer.default_source
t=stripe.Customer.retrieve(s[0]).sources.all(object="card")
tt=t['data']
cc = dict()
for i in tt:
#print (i.id)
#print (i.last4)
if i.id== custom_card:
credit_card_data= i
#print ("ESTA ES LA TARJETA ACTUAL")
cc['last4']= i.last4
cc['cc_brand'] = i.brand
##########################################################################
booking_data.update({ booking_data.update({
'credit_card_data': credit_card_data if credit_card_data else None, 'credit_card_data': credit_card_data if credit_card_data else None,
@ -369,8 +231,6 @@ class BookingPaymentView(LoginRequiredMixin, MembershipRequiredMixin, FormView):
# if not credit_card_needed: # if not credit_card_needed:
# Get or create stripe customer # Get or create stripe customer
# import pdb
# pdb.set_trace()
customer = StripeCustomer.get_or_create(email=self.request.user.email, customer = StripeCustomer.get_or_create(email=self.request.user.email,
token=token) token=token)
if not customer: if not customer:
@ -738,23 +598,6 @@ class OrdersMembershipDetailView(LoginRequiredMixin, DetailView):
return context return context
# class BookingCancelView(FormView):
# success_message = "Your booking has been cancelled"
# model = BookingOrder
# form_class = CancelBookingForm
# def get_success_url(self):
# pk = self.kwargs.get(self.pk_url_kwarg)
# return reverse_lazy('digitalglarus:booking_orders_list', kwargs={'pk': pk})
# def form_valid(self, form):
# booking_order = self.get_object()
# # booking_order.cancel()
# request = self.request
# return HttpResponseRedirect(self.get_success_url())
class OrdersBookingDetailView(LoginRequiredMixin, UpdateView): class OrdersBookingDetailView(LoginRequiredMixin, UpdateView):
template_name = "digitalglarus/booking_orders_detail.html" template_name = "digitalglarus/booking_orders_detail.html"
context_object_name = "order" context_object_name = "order"
@ -865,19 +708,6 @@ class BookingOrdersListView(LoginRequiredMixin, ListView):
return queryset return queryset
############## OLD VIEWS
class CalendarApi(View):
def get(self,request,month,year):
calendar = BookCalendar(request.user,requested_month=month).formatmonth(int(year),int(month))
ret = {'calendar':calendar,'month':month,'year':year}
return JsonResponse(ret)
def post(self,request):
pd = json.loads(request.POST.get('data',''))
ret = {'status':'success'}
CalendarModel.add_dates(pd,request.user)
return JsonResponse(ret)
class ContactView(FormView): class ContactView(FormView):
template_name = 'contact.html' template_name = 'contact.html'
form_class = ContactUsForm form_class = ContactUsForm
@ -890,25 +720,7 @@ class ContactView(FormView):
messages.add_message(self.request, messages.SUCCESS, self.success_message) messages.add_message(self.request, messages.SUCCESS, self.success_message)
return super(ContactView, self).form_valid(form) return super(ContactView, self).form_valid(form)
############## OLD VIEWS
class AboutView(TemplateView):
template_name = "digitalglarus/about.html"
def detail(request, message_id):
p = get_object_or_404(Message, pk=message_id)
context = { 'message': p, }
return render(request, 'digitalglarus/detail.html', context)
def about(request):
return render(request, 'digitalglarus/about.html')
def home(request):
return render(request, 'index.html')
def letscowork(request):
return render(request, 'digitalglarus/letscowork.html')
def blog(request): def blog(request):
tags = ["digitalglarus"] tags = ["digitalglarus"]

View File

@ -95,6 +95,10 @@ class SetPasswordForm(forms.Form):
return password2 return password2
class EditCreditCardForm(forms.Form):
token = forms.CharField(widget=forms.HiddenInput())
class BillingAddressForm(forms.ModelForm): class BillingAddressForm(forms.ModelForm):
token = forms.CharField(widget=forms.HiddenInput()) token = forms.CharField(widget=forms.HiddenInput())

View File

@ -59,11 +59,23 @@ class StripeUtils(object):
self.stripe = stripe self.stripe = stripe
def update_customer_token(self, customer, token): def update_customer_token(self, customer, token):
# customer = stripe.Customer.retrieve(id)
customer.source = token customer.source = token
customer.save() customer.save()
@handleStripeError
def update_customer_card(self, customer_id, token):
customer = stripe.Customer.retrieve(customer_id)
current_card_token = customer.default_source
customer.sources.retrieve(current_card_token).delete()
customer.source = token
customer.save()
credit_card_raw_data = customer.sources.data.pop()
new_card_data = {
'last4': credit_card_raw_data.last4,
'brand': credit_card_raw_data.brand
}
return new_card_data
def check_customer(self, id, user, token): def check_customer(self, id, user, token):
customers = self.stripe.Customer.all() customers = self.stripe.Customer.all()
if not customers.get('data'): if not customers.get('data'):
@ -77,6 +89,12 @@ class StripeUtils(object):
user.stripecustomer.save() user.stripecustomer.save()
return customer return customer
@handleStripeError
def get_customer(self, id):
customer = stripe.Customer.retrieve(id)
# data = customer.get('response_object')
return customer
@handleStripeError @handleStripeError
def create_customer(self, token, email): def create_customer(self, token, email):