I need to implement the Mercado Pago custom checkout to receive payments in my site. To do it I need to run the javascript code to get the card_token_id, like described in this link: https://developers.mercadopago.com/documentation/custom-checkout?lang=en_US.
But my website, for business restrictions, need to get this card_token_id running into a Java code, into my class. I need to run this javascript code into my Java class, get the result, e use him in a http POST. I already tried use ScriptEngine, but not works.
See below the complete code that works in html.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Pagar</title>
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="https://secure.mlstatic.com/org-img/checkout/custom/1.0/checkout.js"></script>
</head>
<body>
<h1>Fluxo de pagamento personalizado (avançado)</h1>
<form action="" method="post" id="form-pagar-mp">
<input id="amount" type="hidden" value="100"/>
<p>Número do cartão: <input data-checkout="cardNumber" type="text" value="4509953566233704"/></p>
<p>Código de Segurança: <input data-checkout="securityCode" type="text" value="123"/></p>
<p>Mês de vencimento: <input data-checkout="cardExpirationMonth" type="text" value="12"/></p>
<p>Ano de vencimento: <input data-checkout="cardExpirationYear" type="text" value="2020"/></p>
<p>Titular do cartão: <input data-checkout="cardholderName" type="text" value="Joao"/></p>
<p>Número do documento: <input data-checkout="docNumber" type="text" value="19313777584"/></p>
<input data-checkout="docType" type="text" value="CPF"/>
<p id="issuersField">Bancos: <select id="issuersOptions"></select>
<p>Parcelas: <select id="installmentsOption"></select>
<p><input type="submit" value="Concluir pagamento"></p>
</form>
<script type="text/javascript">
/* Troque com a sua public_key */
Checkout.setPublishableKey("TEST-cba0f2d5-c989-4c97-8e61-847121530093");
$("input[data-checkout='cardNumber']").bind("keyup",function(){
var bin = $(this).val().replace(/ /g, '').replace(/-/g, '').replace(/\./g, '');
if (bin.length == 6){
Checkout.getPaymentMethod(bin,setPaymentMethodInfo);
}
});
// Estabeleça a informação do meio de pagamento obtido
function setPaymentMethodInfo(status, result){
$.each(result, function(p, r){
$.each(r.labels, function(pos, label){
if (label == "recommended_method") {
Checkout.getInstallments(r.id ,parseFloat($("#amount").val()), setInstallmentInfo);
Checkout.getCardIssuers(r.id,showIssuers);
return;
}
});
});
};
// Mostre as parcelas disponíveis no div 'installmentsOption'
function setInstallmentInfo(status, installments){
var html_options = "";
for(i=0; installments && i<installments.length; i++){
html_options += "<option value='"+installments[i].installments+"'>"+installments[i].installments +" de "+installments[i].share_amount+" ("+installments[i].total_amount+")</option>";
};
$("#installmentsOption").html(html_options);
};
function showIssuers(status, issuers){
var i,options="<select data-checkout='cardIssuerId'><option value='-1'>Escolha...</option>";
for(i=0; issuers && i<issuers.length;i++){
options+="<option value='"+issuers[i].id+"'>"+issuers[i].name +" </option>";
}
options+="</select>";
if(issuers.length>0){
$("#issuersOptions").html(options);
}else{
$("#issuersOptions").html("");
$("#issuersField").hide();
}
};
$("#issuersOptions").change(function(){
var bin = $("input[data-checkout='cardNumber']").val().replace(/ /g, '').replace(/-/g, '').replace(/\./g, '').slice(0, 6);
Checkout.getInstallmentsByIssuerId(bin,this.value,parseFloat($("#amount").val()),setInstallmentInfo);
});
$("#form-pagar-mp").submit(function( event ) {
var $form = $(this);
Checkout.createToken($form, mpResponseHandler);
event.preventDefault();
return false;
});
var mpResponseHandler = function(status, response) {
var $form = $('#form-pagar-mp');
if (response.error) {
alert("Ocorreu um erro: "+JSON.stringify(response));
} else {
var card_token_id = response.id;
$form.append($('<input type="text" id="card_token_id" name="card_token_id"/>').val(card_token_id));
alert("card_token_id: "+card_token_id);
$form.get(0).submit();
}
}
</script>
</body>
</html>
Related
I have to create a form for update some user profile data. I develop this html form but when I submit and I try to get request parameters they all result null.
The form is filled with actual data and then you can modify them refilling with the new one.
Thanks
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Login</title>
<link rel="stylesheet" type="text/css" media="all" href="../CSS/style.css" th:href="#{.../CSS/style.css}"/>
<script type="text/javascript" src="../js/signup.js" th:src="#{/js/signup.js}" defer> </script>
<script type="text/javascript" src="../js/updateProfile.js" th:src="#{/js/updateProfile.js}" defer> </script>
<script type="text/javascript" th:src="#{/js/loadimage.js}" defer ></script> <!--defer fa eseguire js dopo il parsing di html-->
</head>
<body>
<div class="container">
<h1>Profilo Utente</h1>
<div class="form">
<form action="updateprofile" method="post" enctype="multipart/form-data" onsubmit="return formValidation()">
<p>
<label for="username">Username: </label><br>
<input type="text" id="username" name="username" th:attr="value=${session.user.username}" required/><br>
</p>
<p>
<label for="email">Mail: </label><br>
<input type="email" id="email" name="email" th:attr="value=${session.user.email}" required/><br>
</p>
<p>
<label for="password">Password: </label><br>
<input type="password" id="password" name="password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
title="Deve contenere almeno 8 caratteri di cui un numero, una lettera maiuscola e una lettera minuscola." /><br>
</p>
<p>
<label id="text-password-confirm" for="password-confirm">Reinserisci password: </label><br>
<input type="password" id="password-confirm" />
</p>
<p id="password-message" class="error-message"></p>
<p>
Tipo di utente:<br>
<input type="radio" name="usertype" id="manager" value="manager" th:checked="${session.user.isManager!=null && session.user.isManager}" required/>
<label for="manager">Manager</label><br>
<input type="radio" name="usertype" id="worker" value="worker" th:checked="${session.user.isManager!= null && !session.user.isManager}" checked required/>
<label for="worker">Worker</label><br>
</p>
<div id="worker-data">
<p>
<label for="exp">Exp level:</label><br>
<select name="exp" id="exp">
<option value="" disabled selected>Exp level</option>
<option value="LOW" th:selected="${session.user.exp == 'LOW'}">LOW</option>
<option value="MEDIUM" th:selected="${session.user.exp == 'MEDIUM'}">MEDIUM</option>
<option value="HIGH" th:selected="${session.user.exp == 'HIGH'}">HIGH</option>
</select><br>
</p>
<p>
<label for="photo">Profile photo</label><br>
<div id="container"style="position: relative; width:300px;">
<canvas id="canvas_background" width="300px" style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
</div>
<input type="file" name="photo" id="photo" accept="image/*"/><br>
</div>
<!-- TODO: Rivedere i messaggi di errore inseriti -->
<span class="error-message" th:if="${session.signupfailed}">Salvataggio non riuscito</span>
<p>
<input id="buttonModifica" type="button" value="Modifica" />
<input id="buttonAnnulla" type="reset" value="Annulla" />
<input id="buttonAggiorna" type="submit" value="Aggiorna" />
</p>
</form>
</div>
</div>
</body>
</html>
This is java code of the Update Profile controller
public class UpdateProfile extends AbstractServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("sessionUser");
if (user != null && user.isValid()){
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
boolean isManager = request.getParameter("usertype").equals("manager");
String photo;
Level exp;
if (isManager) {
photo = null;
exp = null;
} else {
photo = ImageEncoder.encodeImage(request.getPart("photo"));
exp = Level.valueOf(request.getParameter("exp"));
}
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setIsManager(isManager);
user.setPhoto(photo);
user.setExp(exp);
}
try {
UserDAO userDAO = new UserDAO(connection);
userDAO.updateProfile(user);
success=true;
} catch (SQLException e) {
}
}
This are javascript code included in signup.jsp:
function formValidation(e) {
var confirm_password = document.getElementById("password-confirm");
if (comparePassword(confirm_password, "Le due password non coincidono") ) {
/*e.preventDefault();
window.history.back();*/
return true;
}
return false;
}
function comparePassword(inputtext, alertMsg){
var password = document.getElementById("password");
if(inputtext.value != password.value) {
document.getElementById('password-message').innerText = alertMsg;
inputtext.focus();
return false;
} else {
return true;
}
}
This is javascript code included in updateProfile.jsp:
var username = document.getElementById("username");
var email = document.getElementById("email");
var password = document.getElementById("password");
var passwordConfirm = document.getElementById("password-confirm");
var radioWorker = document.getElementById("worker");
var radioManager = document.getElementById("manager");
var exp = document.getElementById("exp");
var photo = document.getElementById("photo");
var buttonModifica = document.getElementById("buttonModifica");
var buttonAnnulla = document.getElementById("buttonAnnulla");
var buttonAggiorna = document.getElementById("buttonAggiorna");
function init() {
username.readOnly=true;
email.readOnly=true;
password.readOnly=true;
passwordConfirm.hidden=true;
radioManager.disabled=true;
radioWorker.disabled=true;
exp.disabled=true;
photo.disabled=true;
buttonAnnulla.hidden=true;
buttonAggiorna.hidden=true;
buttonModifica.addEventListener("click", abilitaModifica)
password.addEventListener("change", verificaPassword)
}
function abilitaModifica() {
email.readOnly=false;
password.readOnly=false;
exp.disabled=false;
photo.disabled=false;
buttonAnnulla.hidden=false;
buttonAggiorna.hidden=false;
buttonModifica.hidden=true;
}
function verificaPassword() {
passwordConfirm.hidden=false;
}
init();
try to update your servlet code with this one..
#WebServlet(
name = "UpdateProfile",
urlPatterns = {"/updateprofile"})
public class UpdateProfile extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
User user = (User) session.getAttribute("sessionUser");
if (user != null && user.isValid()){
String username = request.getParameter("username");
String password = request.getParameter("password");
String email = request.getParameter("email");
boolean isManager = request.getParameter("usertype").equals("manager");
String photo;
Level exp;
if (isManager) {
photo = null;
exp = null;
} else {
photo = ImageEncoder.encodeImage(request.getPart("photo"));
exp = Level.valueOf(request.getParameter("exp"));
}
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
user.setIsManager(isManager);
user.setPhoto(photo);
user.setExp(exp);
}
try {
UserDAO userDAO = new UserDAO(connection);
userDAO.updateProfile(user);
success=true;
} catch (SQLException e) {
}
}
}
I have added the java script file in the html for a form and it is connected to the java file I want to show data on same page after submit i.e index.html but after the submission it takes me to the register page.
html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="submit" />
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#register").bind('submit',(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, { name: $('#name').val(), email: $('#email').val(),pass: $('#pass').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</form>
</body>
</html>
The forms needs an id in order to be called with the query selector #register.
<form method="post" action="register" id="register">
(document).ready(function() {
$("input[type='radio']").click(function() {
var radioVal = $("input[name='price']:checked").val();
});
}
I need to pass radioVal value to another jsp
Please Take the help of Following Example.
page1.jsp
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var radioVal;
$("input[type='radio']").click(function() {
radioVal = $("[name=radio]:checked").val();
alert(radioVal);
$.post("page2.jsp", {"processId": radioVal })
});
});
</script>
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
page2.jsp
<%
System.out.println(request.getParameter("processId"));
%>
I'm unable to perform "delete" from the HTML form. This is my HTML, what's incorrect here? , also included the RESTservice method that performs deletion. I see the POST is getting invoked after every button click. Any inputs or suggestions ?
create_todo.html
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script>
document.getElementById("delete").addEventListener("click", function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8080/com.dcr.jersey.first/rest/todos", true);
xhr.setRequestHeader("Content-Type", "application/xml");
xhr.setRequestHeader("X-HTTP-Method-Override", "DELETE"); //X-HTTP-Method-Override
xhr.send();
},true);
</script>
</head>
<body>
<form id= "myForm" action="../com.dcr.jersey.first/rest/todos" method="post" >
<label for="id">ID</label>
<input name="id" />
<br/>
<label for="summary">Summary</label>
<input name="summary" />
<br/>
Description:
<TEXTAREA NAME="description" COLS=40 ROWS=6></TEXTAREA>
<br/>
<input type="submit" id="submit" value="Submit" /> <br/>
<button id="delete">Delete</button>
</form>
</body>
</html>
REST method for DELETE from form
#DELETE
#Produces(MediaType.TEXT_HTML)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void delTodo(#FormParam("id") String id,
#Context HttpServletResponse servletResponse) throws IOException {
Todo c = TodoDao.instance.getModel().remove(id);
if(c==null)
throw new RuntimeException("Delete: Todo with " + id + " not found");
else servletResponse.sendRedirect("../create_todo.html");
}
RESTResourceClient to post and delete which works fine
Form form = new Form();
form.param("id","45");
form.param("summary","Summary for id 45");
response = target.path("rest").path("todos").request().post(Entity.form(form));
System.out.println("\nPost by FORM response code is "+ response.getStatus()+"\n");
response = target.path("rest").path("todos/45").request().delete();
I have this script that will enable the submit button once one of the four checkboxes is selected. This script works successfully in chrome on a PC but not on an iPad device using safari. What am I doing wrong?
<!---JQuery Iniialization --->
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.2/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<!--- This script disables submit button until check box is checked.--->
<script>
window.onload = function() {
var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");
checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));
});
}
</script>
Here is my form
<form action="signature_action.cfm?ticketID=#url.ticketID#&TT=#url.TT#&techID=#url.techID#&device=ipad" method="post" NAME="SigForm" id="SigForm">
<input name="equipment_dropped_off" type="checkbox" id="check1" value="equipment_dropped_off" />
<label for="check1"><span class="style1">Equipment Dropped Off </span></label>
<span class="style1">
<input name="work" type="checkbox" id="check2" value="work"/>
<label for="check2">Work performed </label>
<input name="payment" id="check3" type="checkbox" value="payment" />
<label for="check3">Payment Recieved </label>
<input name="equipment_picked_up" id="check4" type="checkbox" value="equipment_picked_up" />
<label for="check4">Equipment Picked Up</label>
<input name="submit" type="submit" id="submit" class='btn-style-mobile' value="Click Here To Accept Signature" disabled>
</form>
$(document).ready(function () {
var checkboxes = $("input[type='checkbox']"),
submitButt = $("#submit");
function allChecked() {
var result = true;
checkboxes.each(function() {
if(!$(this).is(":checked")) {
result = false;
}
});
return result;
}
checkboxes.on('change', function(e){
e.preventDefault();
if(!allChecked()) {
submitButt.attr('disabled','disabled');
} else {
submitButt.removeAttr('disabled');
}
});
});
https://jsfiddle.net/hb7f4k2r/
//If you need this functionality for only one check-box.
//Add a specific class/id to that particular check-box.
$(".specific-checkbox").on('change', function () {
if ($(this).is(':checked')) {
submitButt.removeAttr('disabled');
} else {
submitButt.attr('disabled','disabled');
}
});