Angularjs + Laravel Stripe integration - Response goes to server and other details missing - stripe-payments

i have an Angular Storefront app set up. I have a shopping cart functionality in place and a stripe "pay with card" button etc. pretty much looks like this:
<form action="/#/order" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ stripeApiKey }}"
data-billingAddress=true
data-shippingAddres=true
data-amount="{{ amount }}"
data-name="StoreFront Name"
data-description="Custom-Made Jewellery"
data-image="../images/www/logo.png"
data-locale="auto">
</script>
</form>
Evrything up to this point is working fine. I submit the form and stripe returns the token but the form goes to the server following the route localhost/order (without the # symbol) instead of angular's localhost/#/order.
Why is stripe forcing this redirect? In other words why isn't angular capturing this return call?
Anyways. Then I create a route with Laravel to capture this and dump to inspect the returned data like so:
Route::post('/order', function($request){
dd($request);
});
Yep, data captured by stripe-generated form is returned except amount is missing... I mean everything including stripeToken, buyer's details such as: Name, Email, Billing and Shipping address are returned BUT detail regarding the amount is missing.
Is this normal or I'm I missing something?
Lastly currency is still showing the default: Where can I change currency from say USD to GBP?
Thanks in advance

1/ I don't think Checkout is forcing the redirect, but I don't know enough about Angular to explain what's going on, sorry.
2/ Yes, this is normal. The amount passed to Checkout in the data-amount configuration option is used for display purposes only. The actual amount that is charged is the one you pass in the amount parameter in the charge creation request in your server-side code.
If you need the amount to be user-specified (for instance, if you're taking donations), you'll need to add the amount to the form. Here is a simple JSFiddle to illustrate this case: https://jsfiddle.net/ywain/g2ufa8xr/
3/ You can use the data-currency parameter to change the currency displayed in the Checkout form. Just like data-amount, this is for display purposes only and the actual currency used for the charge is specified by the currency parameter in the charge creation.

This is what i managed to do.
I went with the custom form approach. I had a form template to capture both customer and card inputs in billing.template.html like so:
<form method="POST" id="payment-form">
<span class="payment-errors"></span>
<div>
<label>Name</label>
<input type="text" name="name" data-stripe="name">
</div>
<div>
<label>Email</label>
<input type="text" name="email" data-stripe="address_email">
</div>
<div>
<label>Address Line 1</label>
<input type="text" name="street" data-stripe="address_line1">
</div>
<div>
<label>Postcode</label>
<input type="text" name="postcode" data-stripe="address_zip">
</div>
<div>
<label for="country">Country</label>
<select ng-include="'../templates/_partials/_countrylist.html'"
id="countries" name="country" class="form-control"
name="country" ng-model="country" id="country" size="2"
data-stripe="address_country" required></select>
</div>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" name="cardNumber" size="20" data-stripe="number"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" name="cvc" size="4" data-stripe="cvc"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" name="expMonth" size="2" data-stripe="exp-month"/>
</label>
<span> / </span>
<input type="text" name="expYear" size="4" data-stripe="exp-year"/>
</div>
<button id="customButton">Pay with Card</button>
</form>
I know we are not supposed to use name attribute in those form inputs but i left them so i could use angular validation, but i remove them using jquery before submitting to server.
Now i created a controller to handle the form: BillingController.js. In there i had an "on click" handler which kick started things by getting a hold of the form and doing some preparatory work: disabling button to prevent further clicks and removing those 'dreaded' name attributes, comme ca:
$('#customButton').on('click',function(event) {
var $form = $('#payment-form');
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
//NOW REMOVE THOSE NAME ATTRIBUTES
$form.find('input').removeAttr('name');
// call Stripe object and send form data to get back the token.
// NOTE first argument is $form
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
Now let me quote the documentation here as this is very important to understand: https://stripe.com/docs/tutorials/forms
The important code to notice is the call to Stripe.card.createToken.
The first argument is the form element containing credit card data
entered by the user. The relevant values are fetched from their
associated inputs using the data-stripe attribute specified in the
form.
Next we create stripeResponseHandler(). Remember it was the second argument in Stripe.card.createToken($form, stripeResponseHandler); above which gets called when Stripe returns the token.
function stripeResponseHandler(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and submit
$form.get(0).submit();
}
};
This is copy and paste stuff from stripe's own documentation: https://stripe.com/docs/tutorials/forms. Now, I want to say that, this is where a lot of us were tripping over the fact that form was performing a redirect etc. - notice final line $form.get(0).submit(); . Thats what caused the auto submit, redirecting to what ever action was on form, if u had any (in my case action attribute wasn't necessary as i was doing redirects in my controller).
So i decided to remove $form.get(0).submit() and implemented my own redirect after i was done sending data to the server.
NOTE: Stripe's response will have included data from the $form - try console.log(response); to have an idea of what's being posted back.
FINALLY:
We check if there were any errors returned and if so display them. Otherwise its all good, send data to the server.
The final code looks like:
function stripeResponseHandler(status, response) {
var $form = $('payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
} else {
// response contains id and card, which contains additional card details
var token = response.id;
// prepare data
var data = {
stripeToken: token,
fullName: response.card.name,
street: response.card.address_line1,
postcode: response.card.address_zip,
town: response.card.address_city,
country: response.card.address_country,
last4: response.card.last4
};
// send to server
$http.post('/checkout', data).then(function(result){
// here you can redirect yourself.
window.location.href = "/#/order-complete";
});
}
};
Angular really playing well with stripe here. Check out this link also: https://gist.github.com/boucher/1750368 - learn a lot from it.
I hope it helps someone today. Happy coding!

Stripe doesn't get involved with your form aside from preventing the default action on form submit event and stopping event propagation. Once the checkout process completes, it appends the relevant data to your form and then triggers a form submit event that is handled by HTML / Javascript natively.
I recommend using something like https://github.com/tobyn/angular-stripe-checkout to get your Stripe response handled correctly by Angular.
Otherwise you could add ng-submit="handleStripeCheckout($event)" to your form instead of action="/#/form". When Stripe's checkout process completes, your $scope.handleStripeCheckout method will be run and you can analyze the new form data inside that method.
Edit: Stripe checkout.js actually triggers form.submit(). That's a pretty bad bug on their part considering that almost no browsers handle that correctly. (Form submitted using submit() from a link cannot be caught by onsubmit handler)

Related

Checkbox value is refreshed after page reload in node JS

"I am creating TODO list using Node as backend. after adding every new item, a checkbox is also generating in front of them so I can apply "CSS line-through" to let user know that item is done or of no use. But when I add another item, the page refreshes and that checkbox is unchecked as I am not storing that value anywhere. Can you tell me how to store the value of that checkbox in the backend?
HTML -
<div class="box" >
<% for (var i=0; i<newListItems.length; i++) { %>
<div class="item">
<input type="checkbox" id="checkBox">
<p> <%= newListItems[i] %> </p>
</div>
<% } %>
<form action="/" method="post" class="item">
<input class="inputBox" type="text" name="newItem" placeholder="New item" autocomplete="off" required="required">
<button type="submit" name="list" value=<%= listTitle%>> +</button>
</form>
</div>
Node JS -
const items = [];
app.post("/", function(req, res){
let item = req.body.newItem;
items.push(item);
res.redirect("/");
});
The answer involves a lot of code, so I will give you a set of steps that can help in your case.
You need to change your data scheme. Currently looks like you are just storing the string in an array of items. You need to change it to be array of objects. Each object should have the field task and done. So you could know which task is done or not.
app.post("/", function(req, res) {
let item = req.body.newItem;
items.push({ name: item, done: false });
res.redirect("/");
});
Next step will be adding an endpoint that will be changing the done field of an array item to true.
Then on a front-end you will need to write some JS code that will be sending an HTTP request to the endpoint that marks the task as done. You need to use AJAX call for that, for example, NPM package axios.
Change the template to reflect the changes to the data. e.g. instead of <%= newListItems[i] %> do <%= newListItems[i].name %> and add logic to render checked checkbox based on done property.
It worth to mention, that you should not store data in memory, because once the process is done, you will lose your data. It is okay for learning purposes, but in production, you should use a database.

NodeJS Post request using a Button

I don't know if this is possible or not. All the research I've done has shown that it is possible with a form and text input. But anyways, Using NodeJs & Express I want to be able to click a button on my webpage, and once it's clicked, it sends a post request to my Node.JS server.
Simpler way of saying it:
When button is clicked, send info to the server.
Goal I'm trying to achieve:
When button is clicked, it sends some sort of ID/code/anything to turn on a service from my database. (I have yet to learn how db's work so I am just trying to focus on front end.)
Code I have so far:
app.post("/send", function(req, res){
var newID = req.body.ID;
res.redirect("/action")
});
<form action="/send" method="POST">
<input type="button" name="newID" placeholder="Button">
<button>send</button>
</form>
You do not need to use jQuery or AJAX.
Simply add an input of type submit inside the form tag so that the POST request defined by your form tag is submitted.
Your newID input should be of type text, this allows entering a value in the input field.
The newID value can be retrieved server side with req.body.newID (be sure to use the body-parser middleware).
<form action="/send" method="POST">
<input type="text" name="newID" placeholder="Enter your ID"/>
<input type="submit" value="Click here to submit the form"/>
</form>
For this purposes you should use $.ajax,
example:
$('button').on('click', function() {
$.ajax({
type: 'POST',
url: '/send',
data: { ID: 'someid' },
success: function(resultData) {
alert(resultData);
}
});
});

additional text fields in html form after a numeric entry in another text field

Am using an html form to send data to a sql database using php.
My trouble is that I have a dynamic value for number of items which changes for each order and am trying to avoid having to add an x number of extra text fields for all orders.
A better solution would be to enter a value in a text field which then makes the same number of additional text fields appear in the form.
Is there anyway to accomplish this?
Thanks
OK. So you want to show a number of input fields at the user's request, before pressing the submit button. My first approach would be to do it in javascript.
Let's assume this form:
<form>
<p><input name="myInput1" /></p>
<button type="submit">submit</button>
</form>
You could include an extra button to add a new row:
<form>
<p><input name="myInput1" /></p>
<button type="button" onclick="addInput(this.form)">add input</button>
<button type="submit">submit</button>
</form>
... and the handler function would be something like this:
<script type="text/javascript">
function addInput(form)
{
// Create a new <p><input> node at the end of the form, throughput the DOM API:
// Get the last <p> element of the form
var paragraphs=form.getElementsByTagName("P")
var lastParagraph=paragraphs[paragraphs.length-1]
// Create a new <p> element with a <input> child:
var newParagraph=document.createElement("P")
var newInput=document.createElement("INPUT")
// Name the <input> with a numeric suffix not to produce duplicates:
newInput.name="myInput"+(1+paragraphs.length)
newParagraph.appendChild(newInput)
// Add the created <p> after the last existing <p> of the form:
form.insertBefore(newParagraph, lastParagraph.nextSibling)
}
</script>
(Notice that all the rendering logic is performed in the client side (in HTML + javascript), and when the form is finally submitted, the server will just receive a collection of pairs name + value.)

Bootstrap + jQuery validationEngine make custom ajax validation call onFieldSuccess to update feedback

I am using the jQuery Validation Engine plugin to validate my form. I am also using Bootstrap to give the user feedback (success/fail) of the given input.
Here is how I am initializing the plugin:
jquery
$.validationEngine.defaults.promptPosition = 'inline';
$.validationEngine.defaults.onFieldFailure = function (field) {
console.log('onFieldFailure called');
field.parent().removeClass('has-success').addClass('has-error');
field.nextAll('span').children().removeClass('fa-check').addClass('fa-remove');
};
$.validationEngine.defaults.onFieldSuccess = function (field) {
console.log('onFieldSuccess called');
field.parent().removeClass('has-error').addClass('has-success');
field.nextAll('span').children().removeClass('fa-remove').addClass('fa-check');
};
$form.validationEngine('attach');
I am using CodeIgniter to handle the form server-side. Everything is working great.
html/php
<div class="form-group has-feedback">
<label for="email"><i class="fa fa-asterisk"><span class="sr-only">This field is required</span></i> E-mail Address</label>
<input type="text" class="form-control" id="email" name="email"
data-validation-engine="validate[required, custom[email], ajax[email_exists]]"
data-errormessage-value-missing="This field is required"
data-errormessage="Invalid E-mail address"
value="<?php echo set_value('email'); ?>"
placeholder="your#email.com">
<span class="form-control-feedback"><i class="fa fa-remove"></i></span>
<?php echo form_error('email'); ?>
</div>
Here is my controller (how I'm returning a response):
php
public function ajax_email_exists() {
if ($this->user_model->email_exists($this->input->get('fieldValue'))) {
echo json_encode(array('email', FALSE));
} else {
echo json_encode(array('email', TRUE));
}
}
When the user blurs out of the email field, I do an ajax call email_exists which is working fine as well. Here is what that looks like. It is located in the jquery.validation-engine-en.js file as suggested in the docs.
jquery
'email_exists': {
'url': 'path-to-my-script.php',
'alertTextLoad': '<i class="fa fa-cog fa-spin"></i> Validating, please wait...',
'alertTextOk': '<i class="fa fa-check-circle"></i> E-mail address is valid',
'alertText': '<i class="fa fa-exclamation-triangle"></i> That Email-address already exists'
},
The validation itself is working great. I am getting correct response back - the problem I'm running into is I can't seem to figure out how to make the success of the ajax call to call the onFieldSuccess method. As soon as I blur out of the email field onFieldFailure is called and my input is red. When the ajax validation is complete, I am unable to get rid of the invalid style and apply my valid style. In essence, call the onFieldSuccess method to give the correct feedback.
A thought I had was maybe I need to look at using funcCall instead?
Thank you for your time & suggestions!
EDIT
I've updated my initialize method to add css classes to the elment(s). It seems i'm always getting to addFailureCssClassToField even when I am getting a success result back from the server.
Just in case anyone come across this thread, here is how I came up with a solution.
As mentioned before, all of my validation is/was working correctly. The problem was updating the feedback accordingly. I was unable to update the style(s) to reflect what was happening.
I have updated/cleaned up the plugin code itself so my line numbers are going to be off. That said, around line #1578, you will find this:
jquery
if (options.showPrompts) {
// see if we should display a green prompt
if (msg) {
methods._showPrompt(errorField, msg, "pass", true, options);
options.onFieldSuccess(errorField); // Added this line.
} else {
methods._closePrompt(errorField);
}
}
Because I was getting a success response, I needed to call onFieldSuccess. I am also passing in the field element (jQuery object) to render to.

Disable empty search

I have a photography site driven in part by the 'Photoshelter' service, and I put an embedded search bar in my nav.
<form action="http://brettcole.photoshelter.com/search" method="get">
<input type="text" placeholder="search library" size="15" name="I_DSC">
<input type="submit" value="go">
<input type="hidden" name="I_DSC_AND" value="t">
<input type="hidden" name="_ACT" value="search">
</form>
It allows for a search to be executed with the no search term present, which then returns all 12,000 photos in my archive. Is there a best practice for preventing this, such that the user has to type something or nothing will happen when they click search?
It's also present on my advanced search page. This is generated by a search widget shortcode in the Photoshelter back end. I'd like to apply the same thing here, but not sure how the widgetization of it might affect the process.
Many thanks
You can use the onsubmit attribute of the form element to check if the user has entered information in any fields and then prevent submit based on that.
<script>
function checkValues() {
searchBox = document.getElementById("SearchField");
return searchBox.value != ""; // True will allow submission and false will prevent it
}
</script>
With this...
<form onsubmit="checkValues();" action="http://brettcole.photoshelter.com/search" method="get">
<input type="text" id="SearchField" placeholder="search library" size="15" name="I_DSC">
<input type="submit" value="go">
<input type="hidden" name="I_DSC_AND" value="t">
<input type="hidden" name="_ACT" value="search">
</form>
Should do what you need.
See also this answer: How to grab the onSubmit event for a form?
The actual search isn't working
From the contact page for example, it returns this
http://brettcolephotography.com/contact.html?I_DSC=red&I_DSC_AND=t&_ACT=search
the formula for my search returns is
http://brettcole.photoshelter.com/search?I_DSC=red&I_DSC_AND=t&_ACT=search
this search bar is present on all three of my web properties, personal site, blog, and photoshelter site, all three are tightly integrated to where you can't tell when you're switching between them. It needs to work regardless of where the search is being executed from. Thanks
Here is a function I wrote to disable the search form submitting if the search field is empty. It also focuses the cursor on the search field if the form is not submitted so that the user does not think that search is broken.
This is assuming that jQuery is loaded. Hope this helps!
var preventSearchIfEmpty = function() {
$('form[method="get"]').on( 'submit', function( ev ){
var query = $('input[type="text"]').val(),
queryLength = query.length;
if ( 0 === queryLength ) {
// Make the cursor blink so user is aware it's not broken, they need input to search
$('input[type="search"]').focus();
ev.preventDefault();
return;
}
});
}();

Resources