How can i get a stripe token on my controller with checkout? - javascript

i'm trying to get a stripe token when i use checkout, but when i submit the embeded form i don't have a POST method and i don't know how i can have the token on my php controller too.
Here is my code :
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_WWlLRtqEY2yfJUlfA4TRRcyf',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
console.log(token.id);
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Musée du Louvre',
description: 'Biletterie en ligne',
currency: 'eur',
amount: '{{ price }}' * 100,
email: '{{ mail }}',
allowRememberMe: false,
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
i tried with this :
<form post="" method="post">
my script code
</form>
but when i click on pay the page don't resfresh.
Someone can help me?

The idea is to change the code in the token callback to send the token to your server instead of logging it to the console.
Change your form to have a hidden field for the stripe token id and the email entered by the customer:
<form action="/your/route" method="POST" id="payment-form">
<input type="hidden" id="stripeToken" name="stripeToken" value="tok_XXX" />
<input type="hidden" id="stripeEmail" name="stripeEmail" value="email#example.com" />
</form>
And then change your JS to set those values and submit the form:
token: function(token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#payment-form").submit();
}
This will submit your form and your route on the server will receive the stripeToken and the stripeEmail values in the POST parameters.

Related

VueJS prevent form submission on submit and submit the form on keyup

I have a form that looks like this:
<form id="myForm" action="/searchuser" method="POST" #submit.prevent="onSubmit(inputValue)">
<div class="field">
<label class="label">Name</label>
<div class="control">
<input class="input" type="text" placeholder="Text input" v-model="inputValue" #keyup="onKeyUp" #blur="inputFocused = false">
<ul v-if="inputFocused">
<li v-for="value in values"><a class="panel-block is-primary" :href="value.link">#{{value.title}}</a></li>
</ul>
</div>
</div>
</form>
And in my JavaScript, I have two methods onSubmit and onKeyPress:
<script>
export default {
data() {
return {
inputValue: "",
inputFocused: false,
values: [
{ title: "facebook", link: "http://facebook.com" },
{ title: "twitter", link: "http://twitter.com" },
{ title: "gplus", link: "http://plus.google.com" },
{ title: "youtube", link: "http://youtube.com" }
]
};
},
methods: {
onKeyUp: function() {
document.forms["myForm"].submit();
this.inputFocused = true;
},
onSubmit: function(inputval) {
console.log(inputval);
}
}
};
</script>
What I am trying to achieve is when the user presses a key, I want the form to be submitted but I don't want the page to be redirected to /searchuser route. But as soon as I press a key, the page gets redirected even though I am using the prevent modifier to prevent the submission. How do I prevent it from being redirected and submit it on keyup/keydown only? My goal is to perform an ajax call through onSubmit by sending the inputval to the server.
Vue is not overriding the DOM default behavior, if you decide to
access the DOM API directly while bypassing vue mechanics (e.g.
document.forms)
If you want to submit a form without the redirection, you have to do
ajax request.
you have to use axios (my personal choice). because you are trying to submit the form directly ...in order to keep up with the default form submission data format, I assume you need to sereialize the data as application/x-www-form-urlencoded format. check the docs.
see the code:
onKeyUp method:
onKeyUp: function() {
axios.post("/searchuser", qs.stringify({ inputValue: inputValue }));
this.inputFocused = true;
},
Remember to add axios and qs to your dependencies using npm, and import them on the file.

How use liferay validator with js submit?

I try to use Liferay validator with javascript on Liferay 6.2.
Have a problem is my button must using submit form with a button onlick, but when submit this way Liferay form validator no trigger prevent submit. It just triggers when I using a button type submit.
Here mycode example:
<portlet:actionURL name="updateURL" var="submitURL"/>
<aui:form name="fm2" id="fm2" action="<%=submitURL %>" method="post">
<aui:input name="userName" value='' label="User Name"></aui:input>
<aui:input name="password" value='' label="Password"></aui:input>
<aui:button type="button" name="logIn" id="logIn" value="Login" />
</aui:form>
<aui:script>
AUI().use('aui-base','liferay-form','aui-form-validator',function(A){
A.one("#<portlet:namespace/>logIn").on("click",function(){
submitForm(document.<portlet:namespace />fm2);
});
Liferay.Form.register(
{
id: '<portlet:namespace/>fm2',
fieldRules: [
{
body: '',
custom: false,
errorMessage: '',
fieldName: '<portlet:namespace/>password',
validatorName: 'required'
},
{
body: '',
custom: false,
errorMessage: '',
fieldName: '<portlet:namespace/>userName',
validatorName: 'required'
}
]
});
});
</aui:script>
What i can do ?
How to liferay can prevent event submit with tag, but does not with js?
Here is AUIFormValidator-portlet to demo.
https://drive.google.com/open?id=0B27gY2oYFX7QTTFFdXc3TnZ4d1k
You can do one thing,
<aui:form name="fm2" id="fm2" action="javascript:void(0)" method="post">
It will prevent your submit event and fire the aui form validation.
Now in onClick function you can assign your submit url to form action like below.
$("#<portlet:namespace/>logIn").on("click",function(){
var url = '${submitURL}';
$('#<portlet:namespace />fm2').attr('action', url);
$('#<portlet:namespace />fm2').trigger("submit");
});

Integrating stripe payments (JS and PHP) with a custom amount (JS variable)

I've been trying to figure this out for days with no luck.
I'm trying to implement Stripe Payments Checkout into my website. The payment amount is on the payments page as a JS variable. I was able to get Basic Checkout working, but apparently that can't use a custom amount, or send any data to the PHP processing page (email, and some order attributes). I've been trying to use the Custom Checkout but I can't figure it out. Any help?
So far I have this in config.php:
<?php
require_once('vendor/autoload.php');
$stripe = array(
"secret_key" => "MY SECRET KEY IS HERE",
"publishable_key" => "MY PUBLISHED KEY IS HERE"
);
\Stripe\Stripe::setApiKey($stripe['secret_key']);
?>
and this is in a file called process.php:
<?php
require_once('./config.php');
$token = $_POST['stripeToken'];
$input = $_POST["totalprice"];
$customer = \Stripe\Customer::create(array(
'email' => 'customer#example.com',
'source' => $token
));
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $input,
'currency' => 'usd'
));
echo $input;
?>
And in the initial PHP file I have:
<?php require_once('./config.php'); ?>
<form action="process.php" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="MY PUBLIC TEST KEY IS HERE"
data-amount= amt * 100
data-name="Test Name"
data-description="Widget"
data-image="/img/logo.jpg"
data-locale="auto"
>
<form type=hidden name="totalprice" value=amt*100 action="process.php" method="POST">
</script>
</form>
With that said though, I've had a bunch of other code I've tried before that hasn't worked, so this current code probably should be scrapped. I'd really appreciate any help I can get!
Well, following is the sample code of Custom Integration.
<script src="https://checkout.stripe.com/checkout.js"></script>
<button id="customButton">Purchase</button>
<script>
var handler = StripeCheckout.configure({
key: 'pk_test_6pRNASCoBOKtIshFeQd4XMUh',
image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
locale: 'auto',
token: function(token) {
// You can access the token ID with `token.id`.
// Get the token ID to your server-side code for use.
}
});
document.getElementById('customButton').addEventListener('click', function(e) {
// Open Checkout with further options:
handler.open({
name: 'Stripe.com',
description: '2 widgets',
zipCode: true,
amount: 2000
});
e.preventDefault();
});
// Close Checkout on page navigation:
window.addEventListener('popstate', function() {
handler.close();
});
</script>
The source code is given on this page
So is that what you are looking for?

Passing BraintreeJS paymentnonce payload to ASP.NET Web Form

I'm trying to integrate Chargebee with Braintree using ChargeBee's API+BraintreeJS (easiest to get PCI compliance). Here is the link of methods that could be used (https://www.chargebee.com/docs/braintree.html). Based on that document, I can conclude that these are the steps
1) Generate clientToken using Braintree SDK for .NET
2) Use BraintreeJS to tokenize all hosted fields and send to Braintree API to get payment nonce
3) Use ChargeBee SDK for .NET and send payment nonce to create subscription in ChargeBee
I've managed to do (1) and (2) but my issue is how could I read the payment nonce during postback? I've tried using controller but still getting null value
Here's my code
<script>
var form = document.querySelector('#cardForm');
var authorization = '<%=clientToken%>';
braintree.client.create({
authorization: authorization
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
createHostedFields(clientInstance);
});
function createHostedFields(clientInstance) {
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '16px',
'font-family': 'courier, monospace',
'font-weight': 'lighter',
'color': '#ccc'
},
':focus': {
'color': 'black'
},
'.valid': {
'color': '#8bdda8'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'MM/YYYY'
},
postalCode: {
selector: '#postal-code',
placeholder: '11111'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
// If this was a real integration, this is where you would
// send the nonce to your server.
var noncestr = payload.nonce
alert(noncestr); // Confirm nonce is received.
console.log('Got a nonce: ' + payload.nonce);
$('#paymentmethodnonce').attr("value", noncestr); // Add nonce to form element.
form.submit();
});
}, false);
});
}
</script>
<body>
<div class="demo-frame">
<form action="/" method="post" id="cardForm">
<label class="hosted-fields--label" for="card-number">Card Number</label>
<div id="card-number" class="hosted-field"></div>
<label class="hosted-fields--label" for="expiration-date">Expiration Date</label>
<div id="expiration-date" class="hosted-field"></div>
<label class="hosted-fields--label" for="cvv">CVV</label>
<div id="cvv" class="hosted-field"></div>
<label class="hosted-fields--label" for="postal-code">Postal Code</label>
<div id="postal-code" class="hosted-field"></div>
<div class="button-container">
<input type="submit" class="button button--small button--green" value="Purchase" id="submit" />
</div>
<asp:Label runat="server" ID="lblResult"></asp:Label>
</form>
</div>
<script src="https://js.braintreegateway.com/web/3.8.0/js/client.js"></script>
<script src="https://js.braintreegateway.com/web/3.8.0/js/hosted-fields.js"></script>
</body>
</html>
public partial class Default : System.Web.UI.Page
{
protected string clientToken;
private BraintreeGateway gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "xxx",
PublicKey = "xxx",
PrivateKey = "xxx"
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//generate clienttoken from braintree sdk
clientToken = gateway.ClientToken.generate();
}
else
{
var paymentnonce = Request.Form["paymentmethodnonce"];
}
}
}
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
The callback that you pass to hostedFieldsInstance.tokenize uses a css selector to find an element with ID paymentmethodnonce and store the generated nonce inside of it. However, there's no element with that ID in the HTML that you submitted. Based on the HTML you've shared, that call should fail, and your subsequent attempt to retrieve paymentmethodnonce using Request.Form will also fail.
You should be able to solve this by adding a hidden input element to your form with the id paymentmethodnonce.
<input type="hidden" id="paymentmethodnonce" />
This will give your tokenize callback a place to put the nonce, and it will make the nonce part of the form, which should allow your Request.Form to retrieve it successfully.

form is not refreshing after ajax submit and jquery validate

I have a form which I am submitting to my database, the form includes Jquery Validate plugin and ajax to submit.
The issue I am having is that after I click submit the form does not clear, it updates to database etc but I am just trying to clear the form and css highlight on the input field so someone could add a new record. Any help please?
CODE:
$(document).ready(function () {
$.validator.addMethod("time", function (value, element) {
return this.optional(element) || /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(value);
}, "Please enter a valid time.");
$("#newform").validate({
//validation
debug: false,
rules: {
Name: {
required: true,
minlength: 3,
},
Surname: {
required: true,
},
},
submitHandler: function (form) {
$.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
$('#newform').reset();
});
}
});
});
HTML:
<form name="newform" id="newform" action="" method="POST">
<p>Name:</p>
<input type="text" id="pName" name="sName" /><br />
<p>Surname:</p>
<input type="date" id="pSName" name="pSName" /><br />
<input type="submit" name="submit" value="Submit">
</form>
<div id="results"><div>
You can use the following code to clear your form:
$('#newform').reset();
To focus on a specific <input> then you can use this after the reset() call:
$('input[name="sName"]').focus();
Try the following:
submitHandler: function (form) {
var jqxhr = $.post('process.php', $("#newform").serialize(), function (data) {
$('#results').html(data);
});
jqxhr.done(function() {
$('#newform')[0].reset();
});
}
$('#newform').reset();
The above code will do. But reading your comments I see that you will have to make the ajax call synchronous. Because if its asynchronous, you will clear the form before the submit request is actually processed on server side. That's the reason you see a clear form before process.php
In the ajax call pass async also in the object parameter-
{url:'xyz.com',async:false}

Categories