How to get 3DSecure modal to work with Stripe Payment intents? - javascript

I can make the payments work for test cards NOT requiring 3DSecure authentication. For cards that require it, no modal pops up. In the dashboard the payments will show up with status "The customer must complete an additional authentication step." In these cases I don't even reach the
then(function(result) {
if (result.error) {
alert(result.error.message);
}
else {
alert('Success!');
code part. With non-3ds test cards, this part is working fine.
Debugging the javascript will show me some meaningless exceptions from stripe js script.
Given that it works for some cards, the server site initialization of the payment intent, and passing of the clientsecret, can be ruled out, that part works.
<head runat="server">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://js.stripe.com/v3/"></script>
<style type="text/css">
.auto-style1 {
width: 930px;
}
</style>
</head>
<form id="form1" runat="server">
<div>
<asp:HiddenField ID="hiddenClientSecret" runat="server" />
<input id="cardholder-name" type="text"/>
<!-- placeholder for Elements -->
<div id="card-element" class="auto-style1"></div>
<button id="card-button">
Submit Payment
</button>
</div>
</form>
<script >
var stripe = Stripe('mykey', {locale: 'en'});
var elements = stripe.elements({locale: 'en'});
var cardElement = elements.create('card', {hidePostalCode: true});
cardElement.mount('#card-element');
var cardholderName = document.getElementById('cardholder-name');
var cardButton = document.getElementById('card-button');
var clientSecret = document.getElementById('hiddenClientSecret').value;
cardButton.addEventListener('click', function(ev) {
stripe.handleCardPayment(
clientSecret, cardElement, {
payment_method_data: {
billing_details: {name: cardholderName.value}
}
}
).then(function(result) {
if (result.error) {
alert(result.error.message);
}
else {
alert('Success!');
}
});
});
</script>

OK, I needed to explicitly set button type to "button" - otherwise it does a submit roundtrip to the server: <button type="button" id="card-button">. That code part was taken directly from Stripe, seems they need to be a little more precise in their docs!

Related

Get geolocation on Javascript then submit form if validations are met

When I press submit, I'm trying to capture the current lat-long and after that I'm running some validations and returning true or false depending on if they are met or not. My problem is that the location function is async and I can't get it to work with my function. I've tried many ways to get this to work, and haven't been successful. I'm hoping you guys could shed some light on what I can do to get it to work like I want. What I want is to capture those coordinates, then execute my save function.
$("#save").click(function(){
navigator.geolocation.getCurrentPosition(function(position){
$('#lat-location-end').attr('value', position.coords.latitude);
$('#lon-location-end').attr('value',position.coords.longitude);
saveData();
} function() {
saveData();
});
});
function saveData(){
var odleave = $('#odometer-leave').val();
var odarrival = $('#odometer-arrival').val();
var miles = $('#mil').data('mile');
if (odarrival < odleave){
alert("Odometer: Arrival must not be less than Odometer: Leave");
return false;
}
if (odleave != miles){
if (odleave > miles){
var mile_diff = odleave - miles;
if (mile_diff > 25){
if (!confirm("Your leaving mileage exceeds by " + mile_diff + " miles from your last mileage. Do you want to continue?"))
return false;
}
} else {
if(!confirm("Mileage entered is less than your last mileage. Are you using a new car?"))
return false;
}
//Return the image
var sig = signaturePad.toDataURL("image/png");
sig = sig.split(',')[1];
$('#sig-data').attr('value', sig);
return true;
}
Please, I've been having trouble with this all day and I can't find a way to solve this. I asked something similar this morning but I noticed that the question I was asking was the wrong one. I hope this doesn't get me in trouble. Any help will be appreciated.
Here's a solution that I came up with. For this to work you will be needing both files as it is necessary to make everything work.
semantic.css
semantic.js
it's either you download it locally from semantic-ui or get it on the cdnjs semantic-ui on cdnjs.
Hope it helps.
here is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Get geolocation on Javascript then submit form if validations are met</title>
<link rel="stylesheet" href="http://keith-santiago.com/css/semantic.css">
<style type="text/css">
div#this-form {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div id="this-form" class="ui raised very padded text container segment">
<div class="ui form">
<form class="ui form">
<div class="field">
<label>Odometer Arrival</label>
<input name="odometer-arrival" placeholder="Arrival" type="number">
</div>
<div class="field">
<label>Odometer Leave</label>
<input name="odometer-leave" placeholder="Leave" type="number">
</div>
<div class="field">
<div class="ui checkbox">
<input name="toc" type="checkbox">
<label>I agree to the Terms and Conditions</label>
</div>
</div>
<button class="ui button" type="submit">Submit</button>
</form>
</div>
</div>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script src="http://keith-santiago.com/js/semantic.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$('.ui.button').click(function() {
var $form = $('.ui.form');
var odarrival = parseInt($form.form('get value', 'odometer-arrival'));
var odleave = parseInt($form.form('get value', 'odometer-leave'));
$('.ui.form').form({
fields : {
arrival : {
identifier : 'odometer-arrival',
rules : [{
type: 'empty',
prompt : "please enter a valid number"
}]
},
leave : {
identifier : 'odometer-leave',
rules: [ {
type : 'empty'
}
]
},
toc : {
identifier : 'toc',
rules : [{
type : 'checked'
}]
}
}
});
if ( $('.ui.form').form('is valid')) {
if ( odarrival < odleave ) {
// this block handles everything before submitting. if the condition are not met it will prevent the form from submitting.
return false;
}
}
});
});
</script>
</body>
</html>

Creating website using DirectLineJS

I'm trying to set up the DirectLineJS to work in a website just for testing purposes right now. I've built the DirectLineJS repo and added /built/directLine.js to my website folder following the documentation here https://github.com/Microsoft/BotFramework-DirectLineJS
In the HTML page I'm just using a button to try to send a message through the direct line
<html>
<head>
<meta charset="UTF-8" />
<title>Bot Chat</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://unpkg.com/botframework-directlinejs/directLine.js" type="javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<style>
.wc-chatview-panel {
width: 320px;
height: 500px;
position: relative;
}
.h2 {
font-family: Segoe UI;
}
</style>
</head>
<body>
<h2 style="font-family:Segoe UI;">Welcome to my custom Bot!</h2>
<section class="container">
<input id="clickMe" type="button" value="clickme" onclick="connectDirectLine();" />
</section>
<textarea id="myTextarea">
342 Alvin Road
Ducksburg</textarea>
<p>Click the button to change the contents of the text area.</p>
<button type="button" onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var text = document.getElementById("myTextarea").value;
console.log(text)
}
</script></body>
</html>
<script>
function connectDirectLine() {
import { DirectLine } from 'botframework-directlinejs';
var directLine = new DirectLine({
secret: "mySecret",
});
directLine.postActivity({
from: { id: 'myUserId', name: 'myUserName' }, // required (from.name is optional)
type: 'message',
text: 'a message for you, Rudy'
}).subscribe(
id => console.log("Posted activity, assigned ID ", id),
error => console.log("Error posting activity", error)
);
directLine.activity$
.filter(activity => activity.type === 'message' && activity.from.id === 'yourBotHandle')
.subscribe(
message => console.log("received message ", message)
);
}
</script>
<html
When I run the website the error I'm getting is unexpected token import from import { DirectLine } from "botframework-directlinejs";
how can I properly import the botframework-directlinejs file so that I can use the DirectLine object?
You are mixing TypeScript with JavaScript.
To use Direct Line add the following to the HTML of your page:
<script src="http://unpkg.com/botframework-directlinejs/directLine.js"/>
Then you should delete your Import statement and finally, update the code that creates the DirectLine object to be:
var directLine = new DirectLine.DirectLine({
secret: "mySecret",
});
Notice the DirectLine.DirectLine

client.broadcastMessage is undefined in signalr?

I'm trying to run a simple example of signalr, the example that i'm trying to do is here.
I verified that $.connection.hub.start().done is working fine. The problem is chat.client.broadcastMessage is not executed as i put an alert inside it to make sure but that alert did not execute. Can any one help me to fix my problem? Here is my code:
Chatting page.aspx
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.container {
background-color: #99CCFF;
border: thick solid #808080;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
<!--Script references. -->
<!--Reference the jQuery library. -->
<script src="scripts/jquery-1.6.4.min.js"></script>
<!--Reference the SignalR library. -->
<script src="scripts/jquery.signalR-2.2.1.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script> <!--Add script to update the page and send messages.-->
<script type="text/javascript">
$(function () {
// Declare a proxy to reference the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
// Html encode display name and message.
var encodedName = $('<div />').text(name).html();
var encodedMsg = $('<div />').text(message).html();
// Add the message to the page.
$('#discussion').append('<li><strong>' + encodedName
+ '</strong>: ' + encodedMsg + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
</script>
</body>
</html>
ChatHub.cs
public class ChatHub : Hub
{
//used to send message to all clients
public void send(String name, String message)
{
Clients.All.brodcastMessage(name,message);
}
}
Startup.cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
NOTE: I've figured out that, when i type chat. the dropdown menu does not show me client thus i can not call chat.client.broadcastMessage, why?
I solved the problem by using addMessage instead of brodcastMessage and it works.
here is the code...
chat.client.addMessage = function (name, message) //script side
Clients.All.addMessage(name,message); //inside send method in the hub class

firebug and chrome console both have disappearing console.log messages

I am writing my first site from scratch - I have a form and a function that acts when the form is submitted:
application.js
$(document).ready(function() {
$("#signupform").submit(function(e) {
var name = document.getElementById("pname").value;
var email = document.getElementById("email").value;
var userArray = [];
var user = {
name: name,
email: email
};
console.log(user.email, user.name);
e.preventDefault;
});
});
The message gets logged to the console correctly...but it is only a blip - it disappears right away. Also...any errors I was getting while writing the above code also only showed up as short blips in the console. Just barely long enough to read.
Here is my index.html file...incase it is relevant:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>it IT</title>
<link rel="stylesheet" type="text/css" href="application.css" />
<script src="jquery.js"></script>
<script src="application.js"></script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<h1>it IT</h1>
<div id="signup">
<form id="signupform">
Name: <input type="text" name="pname" id="pname"><br>
Email: <input type="text" name="email" id="email"><br>
<input type="submit" value="sign up">
</form>
</div>
<div id="signin"></div>
<div id="content"></div>
</body>
</html>
preventDefault is a method, you need:
e.preventDefault();
In your question code, the form was submited so console was refreshed.
Actually e.preventDefault is not correct, you need to do this:
$(document).ready(function () {
$("#signupform").submit(function (e) {
e.preventDefault(); // Missing () for preventDefault method
var userArray = [];
var user = {
name: $('#pname').val(), // also, you can get the values here only
email: $('#email').val() // no need to use extra variables for it
};
console.log(user.email, user.name);
});
});
In your browser console go to settings (on the top-right corner) and check the preserve log option. That should prevent the page from reloading.

How to call some JavaScript from an HTML Buttons

I'm new to JavaScript. I have an HTML file with a button, I would need to call the following JS when a button is clicked. Any idea how to do it <input type="submit" value="Get Push Token" />?
Please provide me a sample of code.
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name = "format-detection" content = "telephone=no"/>
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width;" />
<link rel="stylesheet" type="text/css" href="css/index.css" />
<title>Hello Cordova</title>
</head>
<body>
<div class="app">
<h1>Apache Cordova™</h1>
<div id="deviceready">
<p class="status pending blink">Connecting to Device</p>
<p class="status complete blink hide">Device is Ready</p>
<p>Click here to get the Token<input type="submit" value="Get Push Token" />
</div>
</div>
<script type="text/javascript" src="cordova-2.0.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript" src="js/PushToken.js"></script>
<script type="text/javascript">
app.initialize();
</script>
</body>
</html>
Without Using jQuery
In a simple component or application, you wouldn't want to require the entire jQuery library, so the simplest way to do it would be like this:
HTML:
<input type="submit" value="Get Push Token" id="getPushToken" />
JavaScript:
document.getElementById('getPushToken').onclick=function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
}
Using jQuery
If you're building a complex application, there's a good chance you'll be wanting jQuery for something else, in which case you may as well do it like this:
HTML:
<input type="submit" value="Get Push Token" id="getPushToken" />
JavaScript:
$('#getPushToken').click(function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
});
Understanding what's going on
In either case, the key point is that you wrap the code you want to execute in a function, and set it as the handler of the click event for that button. The button will then cause the function to be called.
Using the correct HTML
If the button is not within a form, you should probably use:
<button id="getPushToken">Get Push Token</button>
for the html instead, the JavaScript would be exactly the same.
HTML:
<input type="submit" value="Get Push Token" id="getPushToken" />
JavaScript:
document.getElementById('getPushToken').onclick=function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
}
Anyway you have an input with type="submit", but you haven't any form, that's a bit nonsense.
If you just want a button, use type="button". If you want to submit a form, create a form which contains that input and whose id is, for example, myform. Then,
document.getElementById('myform').onsubmit=function(){
PushToken.getToken(
["getToken"] ,
function(token) {
global.token = token;
},
function(error) {
console.log("Error : \r\n"+error);
}
);
}
...
Put the code inside an event handling function, and then call that function in the onclick of the button.
HTML:
/* you probably want button, not submit, and it should have an ID */
<input type="button" id="someID" value="Get Push Token" />
JS:
document.getElementById('someID').onclick = function () {
// whatever you want to do here
};
Note that there are other ways to bind event handlers, but this is considered the best practice (keep javascript and HTML separated)
Related question: JavasScript event handling best practice?

Categories