Worldpay integration issue in MVC - c#

I am trying to implement worldpay payment method in my MVC project and trying to make a test payment but it shows me this error
You have completed or cancelled your payment.
You have cookies disabled. To complete your payment, enable
cookies by changing the privacy settings in your browser. Then
return to the merchant's site and resubmit your payment.
Your session at WorldPay has timed out. Please return to the
merchant's site and resubmit your payment.
Code that i am trying
<form action="https://secure-test.worldpay.com/wcc/purchase" method="post">
<input name="address1" type="hidden" value="10 Downing Street" />
<input name="amount" type="hidden" value="100.00" />
<input name="cartId" type="hidden" value="DAW" />
<input name="op-DPChoose-VISA^SSL" type="hidden" value="DAW" />
<input name="cardNoInput" type="hidden" value="4444333322221111" />
<input name="country" type="hidden" value="GB" />
<input name="currency" type="hidden" value="GBP" />
<input name="email" type="hidden" value="dave#gov.uk" />
<input name="instId" type="hidden" value="eca6aba9-16b2-4ad0-8019-1212bbb2f152" />
<input name="name" type="hidden" value="Prime Minister" />
<input name="postcode" type="hidden" value="SW1A 2AA" />
<input name="tel" type="hidden" value="020 7925 0918" />
<input name="testMode" type="hidden" value="100" />
<input name="town" type="hidden" value="London" />
<input name="cardCVV" type="hidden" value="1234" />
<input name="cardExp.month" type="hidden" value="1" />
<input name="cardExp.year" type="hidden" value="2017" />
<div class="form-group">
<button class="btn btn-success btn-lg" type="submit">WorldPay Test Checkout</button>
</div>
</form>

Try this for test Order placement through WorldPay
<form action="/complete" id="paymentForm" method="post">
<span id="paymentErrors"></span>
<div class="form-row">
<label>Name on Card</label>
<input data-worldpay="name" name="name" type="text" />
</div>
<div class="form-row">
<label>Card Number</label>
<input data-worldpay="number" size="20" type="text" />
</div>
<div class="form-row">
<label>CVC</label>
<input data-worldpay="cvc" size="4" type="text" />
</div>
<div class="form-row">
<label>Expiration (MM/YYYY)</label>
<input data-worldpay="exp-month" size="2" type="text" />
<label> / </label>
<input data-worldpay="exp-year" size="4" type="text" />
</div>
<input type="submit" value="Place Order" />
</form>
Then add this script in your view file
<script src="https://cdn.worldpay.com/v1/worldpay.js"></script>
<script type="text/javascript">
var form = document.getElementById('paymentForm');
Worldpay.useOwnForm({
'clientKey': 'Your_Client_Key',
'form': form,
'reusable': false,
'callback': function (status, response) {
document.getElementById('paymentErrors').innerHTML = '';
if (response.error) {
Worldpay.handleError(form, document.getElementById('paymentErrors'), response.error);
} else {
var token = response.token;
Worldpay.formBuilder(form, 'input', 'hidden', 'token', token);
console.log(token);
$.ajax({
url: "/Home/payment/",
data: { token: token },
success: function (data) {
},
dataType: "html",
type: "POST",
cache: false,
error: function () {
//Error Message
}
});
form.submit();
}
}
});
</script>
Now add this Order Placement code in your controller
public ActionResult payment(string token)
{
var restClient = new WorldpayRestClient("https://api.worldpay.com/v1", "Your_Service_Key");
var orderRequest = new OrderRequest()
{
token = token,
amount = 500,
currencyCode = CurrencyCode.GBP.ToString(),
name = "test name",
orderDescription = "Order description",
customerOrderCode = "Order code"
};
var address = new Address()
{
address1 = "123 House Road",
address2 = "A village",
city = "London",
countryCode = CountryCode.GB,
postalCode = "EC1 1AA"
};
orderRequest.billingAddress = address;
try
{
OrderResponse orderResponse = restClient.GetOrderService().Create(orderRequest);
Console.WriteLine("Order code: " + orderResponse.orderCode);
}
catch (WorldpayException e)
{
Console.WriteLine("Error code:" + e.apiError.customCode);
Console.WriteLine("Error description: " + e.apiError.description);
Console.WriteLine("Error message: " + e.apiError.message);
}
return Json(null, JsonRequestBehavior.AllowGet);
}

Related

How to handle a send parameter button in asp.net MVC c #?

How to handle a send parameter button in asp.net MVC c #?
<form id="form" name="form" action="" method="post">
<label>Nom : </label>
<input type="text" id="NAME" name="NAME" class="form-control" value=#Model.NAME required />
<input type="submit" value="importer />
</form>
Use Ajax begin Form to get it
In the Html
#using (Ajax.BeginForm("test", "Inicio", new AjaxOptions { HttpMethod = "Post", OnSuccess = "Sucesso(data);" }))
{
<label>Nom : </label>
<input type="text" id="name" name="name" class="form-control" required />
<input type="submit" value="importer" />
}
In The controller
[HttpPost]
public ActionResult test(string name)
{
return Json(new { retorno = name }, JsonRequestBehavior.AllowGet);
}

Can you have 2 buttons in a form, when using Unobtrusive AJAX in Razor Pages?

I have 2 OnPost handlers in the PageModel for a form, is there a way to run Unobtrusive AJAX with different post handlers on each button? I can't seem to find anything on this. Or is there a better way of achieving this through JQuery?
Both handlers seem to be doing the correct function, but I can only run one or the other currently using this method.
Here is what I have:
<form method="post" data-ajax="true" data-ajax-method="post" data-ajax-update="#panel">
<input type="hidden" value="#Model.Options.Count()" name="optionCount" />
<input type="hidden" value="#Model.Product.Name" name="product" />
<input type="hidden" value="#Model.Product.ProductId" name="productId" />
<input type="hidden" value="#Model.Headings" name="headings" />
<input type="hidden" value="#Model.HeadingsString" name="headingsString" />
<input type="hidden" value="#Model.Price" name="price" />
#foreach (var item in Model.Headings.Select((value, index) => new { value, index }))
{
<div class="form-group">
<label class="control-label" id="headingA">#item.value</label>
#foreach (var option in Model.Options.Select((value, index) => new { value, index }))
{
if (item.index == option.index)
{
<select class="form-control" name="#item.index" asp-items="option.value"></select>
}
}
</div>
}
<p>
<strong>Price:</strong>
<div id="panel">#Model.Price</div>
</p>
<button type="submit" class="btn btn-outline-primary">Calculate</button>
<button class="btn btn-outline-primary" asp-page-handler="Cart">Add To Cart</button>
</form>
Thanks for any info!
This is a hack, but seems to be working.
I only needed 1 AJAX post handler in my case, so I edited data-ajax="true/false", with JQuery button click event, which enabled the button (not needing AJAX) to post with its handler.
<form method="post" id="form" data-ajax-method="post" data-ajax-update="#panel">
<input type="hidden" value="#Model.Options.Count()" name="optionCount" />
<input type="hidden" value="#Model.Product.Name" name="product" />
<input type="hidden" value="#Model.Product.ProductId" name="productId" />
<input type="hidden" value="#Model.Headings" name="headings" />
<input type="hidden" value="#Model.HeadingsString" name="headingsString" />
<input type="hidden" value="#Model.Price" name="price" />
#foreach (var item in Model.Headings.Select((value, index) => new { value, index }))
{
<div class="form-group">
<label class="control-label" id="headingA">#item.value</label>
#foreach (var option in Model.Options.Select((value, index) => new { value, index }))
{
if (item.index == option.index)
{
<select class="form-control" name="#item.index" asp-items="option.value"></select>
}
}
</div>
}
<p>
<strong>Price:</strong>
<div id="panel">
<label id="price">#Model.Price</label>
</div>
</p>
<button id="buttonAdd" type="submit" class="btn btn-outline-primary">Calculate</button>
<button id="buttonRemove" class="btn btn-outline-primary" asp-page-handler="Cart">Add To Cart</button>
</form>
The JQuery
<script>
$(document).ready(function () {
$("#buttonAdd").click(function () {
$("#form").attr("data-ajax", "true");
});
});
$(document).ready(function () {
$("#buttonRemove").click(function () {
$("#form").attr("data-ajax", "false");
});
});

Post Async without Redirecting in Razor Pages Web Application

I am trying to make a social networking app, where users can react to posts. But every time someone reacts I need to be able to post the reaction directly to the model without redirecting.
Here is my code so far (with redirecting):
Model:
[BindProperty]
public Models.Table Table { get; set; }
public async Task<IActionResult> OnPostReactAsync(int t)
{
var reaction = new Models.Table
{
Reaction = Table.Reaction,
PostId = t,
UserName = _userManager.GetUserName(User)
};
_context.Table.Add(reaction);
await _context.SaveChangesAsync();
return Redirect("./Index");
}
View:
<form method="post" enctype="multipart/form-data">
<div class="form-group">
<input name="t" value="#item.ID" class="form-control" style="display:none;" />
</div>
<div class="form-group">
<input asp-for="Table.Reaction" id="#item.ID x" type="radio" value="true" onclick="document.getElementById('cal').click()" />
<label class="r good" for="#item.ID x"></label>
<input asp-for="Table.Reaction" id="#item.ID y" type="radio" value="false" onclick="document.getElementById('cal').click()" />
<label class="r bad" for="#item.ID y"></label>
</div>
<div class="form-group">
<input type="submit" id="cal" asp-page-handler="React" value="submit" style="display:none;" class="btn btn-default" />
</div>
</form>

Problems routing with JSON

I'm working with JSON. But apparently I'm doing something wrong with my calls, because I'm not getting into the GetJSON_Register inside the AccountController. I'm no expert in Javascript at all, but I think it's a routing problem in my script.
As I said I'm not very good with Javascript so I'm just going to post all of my functions:
Register.cshtml
<form action="" method="post" role="form">
<div class="form-group">
<label for="email">Email</label>
<input class="form-control" type="email" id="register-email" placeholder="Enter email" value="" required="required" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input class="form-control" type="password" id="register-password" placeholder="Enter password" value="" required="required" />
</div>
<div class="form-group">
<label for="repeatPassword">Repeat Password</label>
<input class="form-control" type="password" id="register-repeatPassword" placeholder="Repeat password" value="" required="required" />
</div>
<hr />
<div class="form-group">
<label for="firstname">Firstname</label>
<input class="form-control" type="text" id="register-firstname" placeholder="Enter firstname" value="" required="required" />
</div>
<div class="form-group">
<label for="lastname">Lastname</label>
<input class="form-control" type="text" id="register-lastname" placeholder="Enter lastname" value="" required="required" />
</div>
<button type="submit" class="btn btn-success" id="register-btn">Register</button>
<div id="message-register">
<span></span>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$('#register-btn').click(function () {
registera();
});
});
function registera() {
var $email = $('#register-email'),
$password = $('#register-password'),
$firstname = $('#register-firstname'),
$lastname = $('#register-lastname'),
$message = $('#message-register.span');
$message.className = 'alert';
showLoadingText($message);
register($email, $password, $firstname, $lastname, function(data) {
if (data.IsValid) {
$message.html('');
$message.className = '';
} else {
$message.className = 'alert alert-danger';
$message.html(data.Message);
}
});
};
</script>
script.js
function register(email, password, firstname, lastname) {
$.getJSON("/Account/GetJson_Register", { email: email, password: password, firstname: firstname, lastname: lastname }, function (data) {
return data;
});
};
AccountController.cs
public ActionResult GetJSON_Register(string email, string password, string firstname, string lastname)
{
string message = "";
bool success = true;
repository.Register(email, password, firstname, lastname);
if(Error.Instance.Message != "")
{
message = Error.Instance.Message;
success = false;
}
return Json(new { IsValid = success, Message = message }, JsonRequestBehavior.AllowGet);
}
EDIT
Tried changing the
<button type="submit" class="btn btn-success" id="register-btn">Register</button>
into
<input type="button" class="btn btn-success" id="register-btn" onclick="registera()" value="Register" />
and removed the .click event.
Now in my Chrome Javascript Console I get this message when clicking the button
Uncaught InvalidStateError: Failed to read the 'selectionDirection' property from 'HTMLInputElement': The input element's type ('email') does not support selection. jquery-latest.min.js:4
Vc jquery-latest.min.js:4
Vc jquery-latest.min.js:4
m.param jquery-latest.min.js:4
m.extend.ajax jquery-latest.min.js:4
m.(anonymous function) jquery-latest.min.js:4
m.extend.getJSON jquery-latest.min.js:4
register script.js:63
registera Register:213
onclick Register:180
GET http://localhost:1317/d61bfd81ee4f49eaae35adc38c5d9ea2/arterySignalR/ping?r…2Flocalhost%3A1317%2FAccount%2FRegister&browserName=Chrome&_=1411294396408 404 (Not Found) browserLink:37
send browserLink:37
p.extend.ajax browserLink:37
i.transports._logic.pingServer browserLink:62
(anonymous function) browserLink:62
I've found a solution. It seems like I'm passing an object from my Register.cshtml to the register function in script.js which takes in a value not an object.
So the solution is to change in Register.cshtml
register($email, $password, $firstname, $lastname, function(data) {
if (data.IsValid) {
$message.html('');
$message.className = '';
} else {
$message.className = 'alert alert-danger';
$message.html(data.Message);
}
});
into
register($email.val, $password.val, $firstname.val, $lastname.val, function(data) {
if (data.IsValid) {
$message.html('');
$message.className = '';
} else {
$message.className = 'alert alert-danger';
$message.html(data.Message);
}
});

Jquery Validation for a single field

My form is
#using (Html.BeginForm("Create", "Account", FormMethod.Post, new { #class = "CreateUser" ,id="createform"}))
{
#Html.ValidationSummary();
<div class="field"><label>User Name*</label></div><input name="UserName" type="text" />
<div class="field"><label>Name</label></div><div class="field1"><input name="FirstName" type="text" placeholder="First Name"/><input name="Middlename" type="text" placeholder="Middle Name" /><input name="LastName" type="text" placeholder="Last Name" /></div>
<div class="field"><label>Email*</label></div><input name="Email" type="text" />
<div class="field"><label>Mobile*</label></div><div class="field2"><input name="CountryCode" type="text" placeholder="Country Code" /><input name="Mobile" type="text" placeholder="Mobile Number" /></div>
<div class="field"><label>Language</label></div><input name="Language" type="text" />
<div class="field"><label>Expiry Date*</label></div><input name="Expiry" type="text" id="datepicker" />
<input id="send" class="subbtn" type="submit" value="Create"/>
How can I validate only user name field using jQuery?
if your need required field validator, you can use something like this(JS):
<input name="UserName" type="text" id="UN"/>
var textBox = document.getElementById('UN');
if(textBox=='')
//your error message
It looks like you want make user name a mandatory field. If it is so you need to add following attribute to your user name input control:
<input name="UserName" type="text" data-val="true" data-val-required="User name field is required."/>
Also you need to configure unobtrusive validation here is the link how to do it: http://bradwilson.typepad.com/blog/2010/10/mvc3-unobtrusive-validation.html
$(document).ready(function(){
$('#createform').submit(function(){
var user_name = $('input:first').val();
if(user_name == /*whatever you want to test*/){
//doesn't pass test
this.preventDefault();
alert("Username error");
} else {
this.submit();
}
});
});

Categories

Resources