Hi I am trying to integrate worldpay on my asp.net website.
I have used this code to achieve the integration.
//test environment url
string url = "https://secure-test.worldpay.com/wcc/purchase";
//get all form elements
NameValueCollection formData = new NameValueCollection();
formData["testMode"] = "100";
//all the form fields here
//make the call to submit form data
WebClient webClient = new WebClient();
byte[] responseBytes = webClient.UploadValues(url, "POST", formData);
string response = Encoding.UTF8.GetString(responseBytes);
inputdiv.Visible = false;
outputdiv.Visible = true;
outputdiv.InnerHtml = response;
Basically I am getting the response and displaying it on a div. Everything works, but the links are having relative path which shouldn't be the case. Except the image urls, all other urls should point to worldpay. how to achieve this?
Any suggestion will be much appreciated.
Please try this, hope this would help a lot.
Html
<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>
SCRIPT
<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>
Serve Side Code C#
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
I am trying to create a new instance of a model from Angular with an ASP.NET backend. However I am facing validation errors saying that the fields are required.
This is what I have tried - template :
<h1>Add employee : </h1>
<form [formGroup]="form">
<label for="EmployeeName">Employee Name : </label>
<input type="text" formControlName="EmployeeName">
<label for="Department">Employee Department: </label>
<input type="text" formControlName="Department">
<label for="DateOfJoining">Date of joining : </label>
<input type="date" formControlName="DateOfJoining">
<label for="fileimage">Main image</label>
<input type="file" accept="image/*" fomrControlName="fileimage" (change)="onImageUpload($event)">
<button (click)="onSubmit()">Create Employee</button>
</form>
This is the Angular component:
ngOnInit(): void {
this.form=this.formBuilder.group({
EmployeeName:[''],
Department:[''],
DateOfJoining:[''],
fileimage:['', Validators.required]
})
}
onImageUpload(event) {
const file = event.target.files[0];
if (file) {
this.form.patchValue({fileimage:file});
this.form.get('fileimage').updateValueAndValidity();
const fileReader = new FileReader();
fileReader.onload = ()=> {
this.imageDisplay=fileReader.result;
};
fileReader.readAsDataURL(file);
}
}
onSubmit() {
const Employee : Employee = {
EmployeeName:this.form.get('EmployeeName').value,
Department:this.form.get('Department').value,
};
this.imageService.createEmployee(Employee, this.form.get('fileimage').value).subscribe(
()=>{
console.log("Employee Created")
},
()=>{
console.log("Error in Employee Creation")
}
);
}
This is the service I am working with :
createEmployee(employee:Employee, file:File):Observable<ArrayBuffer>{
let headers = new Headers();
headers.append('Content-Type', 'multipart/form-data;boundary=<calculated when request is sent>');
const options = {
headers: new HttpHeaders({
'Content-Type': 'multipart/form-data;boundary=<calculated when request is sent>'
}),
body: {}
}
return this.http.post<ArrayBuffer>(`${this.apiURLEmployee}`, {employee, file}, options)
}
And finally this is my backend endpoint :
public IActionResult Post([FromForm]Employee emp, IFormFile file)
{
MongoClient dbClient = new MongoClient(_configuration.GetConnectionString("EmployeeAppCon"));
int LastEmployeeId = dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").AsQueryable().Count();
emp.EmployeeId = LastEmployeeId + 1;
string wwwRootPath = _hostEnvironment.WebRootPath;
if (file != null)
{
string filename = Guid.NewGuid().ToString();
var uploads = Path.Combine(wwwRootPath, #"images\employee");
var extension = Path.GetExtension(file.FileName);
Uri domain = new Uri(Request.GetDisplayUrl());
if (emp.PhotoFileName != null)
{
var oldImagePath = Path.Combine(wwwRootPath, emp.PhotoFileName.TrimStart('/'));
if (System.IO.File.Exists(oldImagePath))
{
System.IO.File.Delete(oldImagePath);
}
}
using (var fileStreams = new FileStream(Path.Combine(uploads, filename + extension), FileMode.Create))
{
file.CopyTo(fileStreams);
}
emp.PhotoFileName = domain.Scheme + "://" + domain.Host + (domain.IsDefaultPort ? "" : ":" + domain.Port) + "/images/employee/" + filename + extension;
}
dbClient.GetDatabase("BDD").GetCollection<Employee>("Employee").InsertOne(emp);
return Json("Employee added successfully");
}
The validation errors are from the backend. Here is the error :
Error Image
Request
Payload
I am trying to send a multipart form consist of text and file type using knockoutjs.
There is an error regarding data-bind file.
Here's my formView:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12">
<label class="control-label">Supplier</label>
<input type="text" name="Supplier" id="Supplier" data-bind="value: Supplier" class="form-control col-md-8 form-control-sm" required />
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="control-label">Picture</label>
<input type="file" name="fileInput" id="fileInput" data-bind="file: {data: fileInput, reader: someReader}" class="form-control" />
</div>
</div>
</div>
#section scripts {
<script src="~/Scripts/SDSScripts/RegisterSdsView.js"></script>
}
ViewModel:
function RegisterSdsView() {
var self = this;
self.Supplier = ko.observable();
self.fileInput = ko.observable();
someReader = new FileReader();
self.RegisterSds = function () {
if (self.errors().length > 0) {
self.errors.showAllMessages();
return;
}
var Supplier = self.Supplier();
var fileInput = self.fileInput();
$.ajax({
url: '/SdsView/RegisterSds',
cache: false,
type: 'POST',
data: {Supplier, fileInput},
success: function (data) {
//some code
},
error: function (data) {
//some code
}
});
}
}
ko.applyBindings(new RegisterSdsView());
Controller:
public ActionResult RegisterSds(string Supplier, HttpPostedFileBase fileInput)
{
var db = new SDSDatabaseEntities();
if (fileInput.ContentLength > 0)
{
string fileName = Path.GetFileNameWithoutExtension(fileInput.FileName);
string fileExtension = Path.GetExtension(fileInput.FileName);
string path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
fileInput.SaveAs(path);
var doc = new SDSDocument()
{
DocName = fileName,
DocType = fileExtension,
DocPath = path
};
db.SDSDocuments.Add(doc);
}
db.SaveChanges();
var result = new { status = "OK" };
return Json(result, JsonRequestBehavior.AllowGet);
}
The problem is the fileInput(viewModel) return null to my controller(HttpPostedFileBase fileInput).
Am I doing these the right way?
This is actually my very first C# .NET project. I can't seem to find a good example related to knockoutjs file data-bind. Basically how to POST Based64 to controller?
Here the api that I use https://github.com/TooManyBees/knockoutjs-file-binding
Well I solved it. I gonna update it here just in case. Basically I just have to POST Base64 string to controller via FormData. I don't know why my previous method cannot send large string value, maybe there are limitation on POST method or browser on how large you can send a data via AJAX.
Here is the reference https://stackoverflow.com/a/46864228/13955999
view:
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<li><input type="checkbox" name="qualitycheck"/><span>item.qualityName</span></li>
}
}
Controller:
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
}
I want to pass multiple selected value to the controller
Your View Code Should be :
#using (Ajax.BeginForm("Searchbyquality", "Health", new AjaxOptions { HttpMethod = "POST" }))
{
foreach (var item in Model.QualityModel)
{
<div class="checkbox">
<label>
<input type="checkbox"
name="qualitycheck"
value="#item.qualityName" /> #item.qualityName
</label>
</div>
}
#*<div class="form-group text-center">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>*#
}
For without Submit button you have to add jQuery Code to call controller action :
$( document ).ready(function() {
$(":checkbox").change(function() {
if(this.checked) {
var qualitycheck_data = { 'qualitycheck': [] };
$('input:checked').each(function ()
{
if(this.name == 'qualitycheck') qualitycheck_data['qualitycheck'].push($(this).val());
});
var path = "/Health/Searchbyquality";
$.ajax({
url: path, type: "POST", cache: "false",
dataType: "json", contentType: "application/json; charset=utf-8",
data: JSON.stringify(qualitycheck_data),
traditional: true,
converters: {'text json': true}
}).success(function (responseText) {
//Success result
window.location.assign(responseText);
}).error(function (responseText){
swal("Error!", "Test 1", "error");
});
//swal("Error!", "Test 2", "error");
}
});
});
And your Controller Action :
[HttpPost]
public ActionResult Searchbyquality(string[] qualitycheck )
{
//code of searching
return View("");
}
cheers !!
I am trying to make a trivial call to a SQL Server 2000 database using Angular's $http service. Angular factory containing the $http:
var RegistrationFactory = function ($http, $q, SessionService) {
return function (email, password, confirmPassword) {
var result = $q.defer();
$http({
method: 'POST',
url: SessionService.apiUrl + '/api/Account/Register',
data: { Email: email, Password: password, ConfirmPassword: confirmPassword },
headers: { 'Content-Type': 'application/json' }
})
.success(function (response) {
result.resolve(response);
})
.error(function (response) {
result.reject(response);
});
return result.promise;
}
}
RegistrationFactory.$inject = ['$http', '$q', 'SessionService'];
And inside the AccountController:
[HttpPost]
[AllowAnonymous]
public async Task<bool> Register(RegisterViewModel model)
{
string queryString = "INSERT INTO Northwind VALUES('test', 'values')";
SqlConnection cnxn = new SqlConnection(WebConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand(queryString, cnxn);
cnxn.Open();
command.ExecuteNonQuery();
cnxn.Close();
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email
};
var result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return false;
}
await SignInManager.SignInAsync(user, false, false);
return true;
}
This program is merely trying to show that the SQL-related codes are executed upon the RegistrationFactory being utilized.
The Register.cshtml view:
<form ng-submit="register()">
<label for="emailAddress">Email Address:</label>
<input id="emailAddress" type="text" ng-model="registerForm.emailAddress" required />
<label for="password">Password:</label>
<input id="password" type="password" ng-model="registerForm.password" required />
<label for="confirmPassword">Password:</label>
<input id="confirmPassword" type="password" ng-model="registerForm.confirmPassword" required />
<button type="submit">Register</button>
</form>
And the RegisterController.js that handles above view:
var RegisterController = function ($scope) {
$scope.registerForm = {
emailAddress: '',
password: '',
confirmPassword: '',
registrationFailure: false
};
$scope.register = function () {
var result = RegistrationFactory($scope.registerForm.emailAddress, $scope.registerForm.password, $scope.registerForm.confirmPassword);
result.then(function (result) {
if (result.success) {
$location.path('/routeOne');
} else {
$scope.registerForm.registrationFailure = true;
}
});
}
}
RegisterController.$inject = ['$scope', '$location', 'RegistrationFactory'];
I am trying to figure out how to actually execute the statement as the result of my $http. Additionally, being able to pass data through the 'POST' would be awesome. And, yes, it has to be for SQL Server 2000, so Entity Framework is not an option. Thanks, everyone!
im trying knockout doing a little test and i have not been able to do this very basic thing with knockout.. i want to return a list from my controller then take that list with my knockout viewmodel and finally bind it to a dropdown in my view.
i have this controller:
#RequestMapping(value="/getUsers", method = RequestMethod.GET)
public List<User> returnUsers(#ModelAttribute User user) {
User user1=new User(), user2, user3 ;
List<User>users=new ArrayList<User>();
user1.setLastName("adsfa");
user1.setName("adfds");
user1.setAge(26);
user2=new User();
user2.setLastName("testLastName2");
user2.setName("testName2");
user2.setAge(45);
user3=new User();
user3.setLastName("testLastName2");
user3.setName("testName3");
user3.setAge(33);
users.add(user1);
users.add(user2);
users.add(user3);
return users;
}
this is my knockout viewmodel:
function viewModel() {
this.name = ko.observable("bob");
this.lastName = ko.observable("smith");
this.age = ko.observable(26);
this.validationMessage = ko.observable();
this.users = ko.observableArray([]);
this.loadUsers(); //with this function call i want to initialize users with my controller data.
}
//this funcion should get the data from my controller
viewModel.prototype.loadUsers = function() {
var tmp = this.users();
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
/*
this.Age = ko.dependentObservable({
read: this.age,
write: function (value) {
if (!isNaN(value)) {
this.age(value);
this.validationMessage("");
}
else {
this.validationMessage("Age must be a number!");
}
},
owner: viewModel
});
*/
var save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
ko.applyBindings(new viewModel());
this is my view:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
</head>
<h1>Testing</h1>
<p>
<a href="${pageContext.request.contextPath}/specRunner" target=_blank>Launch Test Runner</a>
</p>
First Name: <input type="text" data-bind="
value: name,
valueUpdate : 'afterkeydown'
"/>
<br />
Last Name: <input type="text" data-bind="value:lastName, valueUpdate : 'afterkeydown'" />
<br />
Age: <input type="text" data-bind="value: age, valueUpdate : 'afterkeydown'" />
<Br />
<!--p>Destination country: <select data-bind=" options : availableCountries"></select></p-->
<Br />
<span data-bind="text: validationMessage" style="color:Red"></span>
<div>
<h2>Details:</h2>
<hr />
First Name: <span data-bind="text:name"></span> <br /><br />
Last Name: <span data-bind=" text:lastName"></span><br /><br />
Age: <span data-bind="text:age"></span><br />
<button data-bind="click:save">Submit</button>
<p>Usuarios: <select data-bind="options:users, value:name" type="text"></select></p>
</div>
<script src="resources/js/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="resources/js/knockout-3.0.0.js" type="text/javascript"></script>
<script type="text/javascript" src="resources/js/viewModel.js"> </script>
</body>
</html>
don't use this.users() and use prototype for save method also.
viewModel.prototype.loadUsers = function() {
var tmp = this.users;
$.get("/vacation_booking/getUsers", function (data) {
tmp(ko.toJS(data));
log.info("Usuarios:" + data);
});
}
viewModel.prototype.save = function(){
// var jsonData = ko.toJSON(viewModel);
// alert("Could now send this to server: " + JSON.stringify(jsonData));
$.ajax({
url: "/vacation_booking/save",
dataType: "json",
type: "POST",
data: "name=" + this.name() + "&lastName=" + this.lastName() + "&age=" + this.age(),
success: function(data){
alert("Successful");
},
failure: function(){
alert("Unsuccessful");
}
});
}
second thing you can return json data directly from controller.
check this sample at fiddle