Uncaught Error: No value passed to payment - c#

ASP.Net Framework 4.5.2 on Windows
I am configuring my integration with paypal using Server-side REST, my code is the same that this https://github.com/paypal/PayPal-NET-SDK/blob/develop/Samples/Source/PaymentWithPayPal.aspx.cs, no diference.
Payment model
The Payment model created are this:
{"intent":"sale","payer":{"payment_method":"paypal"},"transactions":[{"amount":{"currency":"USD","total":"100.00","details":{"subtotal":"75","shipping":"10","tax":"15"}},"description":"Transaction description.","invoice_number":"608961","item_list":{"items":[{"sku":"sku","name":"Item Name","quantity":"5","price":"15","currency":"USD"}]}}],"redirect_urls":{"return_url":"http://localhost:51379/PaymentWithPayPal.aspx?guid=60896","cancel_url":"http://localhost:51379/PaymentWithPayPal.aspx?guid=60896&cancel=true"}}
After Payment model is created
I create the payment at this line
var createdPayment = payment.Create(apiContext);
CreatedPayment
And the createdPayment variable is equals to:
{"id":"PAY-8TG15254J2564684XLFQUQHQ","intent":"sale","payer":{"payment_method":"paypal"},"transactions":[{"related_resources":[],"amount":{"currency":"USD","total":"100.00","details":{"subtotal":"75.00","shipping":"10.00","tax":"15.00"}},"description":"Transaction description.","invoice_number":"608961","item_list":{"items":[{"sku":"sku","name":"Item Name","quantity":"5","price":"15.00","currency":"USD"}]}}],"state":"created","create_time":"2017-07-08T21:01:18Z","links":[{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-8TG15254J2564684XLFQUQHQ","rel":"self","method":"GET"},{"href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-6PE445186E489192C","rel":"approval_url","method":"REDIRECT"},{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAY-8TG15254J2564684XLFQUQHQ/execute","rel":"execute","method":"POST"}]}
Error
after, the code continues without any error, and when it finish, the paypal window closes and I am getting the next error on javascript:
Error: No value passed to payment
Object {stack: "Error: No value passed to payment↵ at https://w…://www.paypalobjects.com/api/checkout.js:2390:13)", errtype: "[object Error]", timestamp: 1499547706746, windowID: "5148517b93", pageID: "510d0e1522"…} country:"US" env:"sandbox" errtype:"[object Error]" host:"www.sandbox.paypal.com" lang:"en" pageID:"510d0e1522" path:"/webapps/hermes/button" referer:"http://localhost:51379" stack:"Error: No value passed to payment↵ at https://www.paypalobjects.com/api/checkout.js:7986:52↵ at https://www.paypalobjects.com/api/checkout.js:7417:54↵ at ZalgoPromise.dispatch (https://www.paypalobjects.com/api/checkout.js:7441:27)↵ at ZalgoPromise.resolve (https://www.paypalobjects.com/api/checkout.js:7386:22)↵ at https://www.paypalobjects.com/api/checkout.js:7363:48↵ at https://www.paypalobjects.com/api/checkout.js:7417:54↵ at ZalgoPromise.dispatch (https://www.paypalobjects.com/api/checkout.js:7441:27)↵ at ZalgoPromise.resolve (https://www.paypalobjects.com/api/checkout.js:7386:22)↵ at https://www.paypalobjects.com/api/checkout.js:7440:42↵ at ZalgoPromise.dispatch (https://www.paypalobjects.com/api/checkout.js:7441:27)↵ at Object._RECEIVE_MESSAGE_TYPE.(anonymous function) [as postrobot_message_response] (https://www.paypalobjects.com/api/checkout.js:2471:118)↵ at receiveMessage (https://www.paypalobjects.com/api/checkout.js:2369:77)↵ at messageListener (https://www.paypalobjects.com/api/checkout.js:2390:13)" timestamp : 1499547706746 uid : "8cb15883be" ver : "4.0.89" windowID : "5148517b93" __proto__ : Object
This is my PayPal CheckoutJS
paypal.Button.render({
env: 'sandbox',
commit: true,
payment: function () {
// Set up a url on your server to create the payment
var CREATE_URL = "#Url.Action("MakePaymentWithPayPal", "Payment")";
// Make a call to your server to set up the payment
return paypal.request.post(CREATE_URL)
.then(function (res) {
console.log("res");
console.log(res);//this is always empty
return res.paymentID;
}).catch(function (err) {
reject("err");
reject(err);
});
},
onAuthorize: function (data, actions) {
// Set up a url on your server to execute the payment
var EXECUTE_URL = '/demo/checkout/api/paypal/payment/execute/';
// Set up the data you need to pass to your server
var data = {
paymentID: data.paymentID,
payerID: data.payerID
};
// Make a call to your server to execute the payment
return paypal.request.post(EXECUTE_URL, data)
.then(function (res) {
window.alert('Payment Complete!');
console.log(res);
});
}
}, '#paypal-button');`

Thanks to bluepnume for open my eyes
I changed the method from Void type to String type => this change is for return the response from my server to Client-Side js
At the end of the create payment code, I added one line to save the guid number and the return
HttpContext.Current.Session.Add("guid", guid); //we need this number on authorize payment
HttpContext.Current.Session.Add(guid, createdPayment.id);
HttpContext.Current.Session.Add("flow-" + guid, this.flow);
return JsonConvert.SerializeObject(createdPayment, Formatting.None); //I return the created payment
Now at the JS I changed the return by the correct payment id
payment: function () {
var CREATE_URL = "#Url.Action("MakePaymentWithPayPal", "Payment")";
return paypal.request.post(CREATE_URL)
.then(function (res) {
//return res.paymentID; //earlier line
return res.id;
});
},
And at the begin of the authorize payment code, I exchange the line with which the guid was retrieved to continue the transaction and at the end I return the executed payment
//var guid = HttpContext.Current.Request.Params["guid"]; //earlier line
string guid = HttpContext.Current.Session["guid"].ToString();
//code...
return JsonConvert.SerializeObject(executedPayment, Formatting.None);
and this is ready to make payments.

Related

SignalR error Error: Failed to invoke 'Methodname' due to an error on the server

i am getting this error Error: Failed to invoke 'MoveLobbyCard' due to an error on the server. when trying to perform an action in lobby
my js code:
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();
connection.start().then(function () {
}).catch(function (err) {
return console.error(err.toString());
});
connection.on("UserConnected", function (ConnectionId) {
$("#userlist").append($("<li>").text(ConnectionId + "has joined"));
var lobbyID = $('#lobbyID').text();
connection.invoke("JoinLobby", lobbyID).catch(function (err) {
return console.error(err.toString());
});
});
connection.on("CardMoved", function (id) {
$('#'+id).addClass("moved");
});
$('.card').on("click", function (){
var id = $(this).attr("id");
connection.invoke("MoveLobbyCard",id,lobbyID).catch(function (err) {
return console.error(err.toString());
});
});
it does add to groups but i have no idea whats causing the error
For me the error was caused by a method signature on the hub expecting an integer but javascript providing it (a number) as a string. I changed the hub to accept a string and parsed it to an integer before use and it was all good.
the error was caused due var id not being a global variable so instead of the id it took the entire span.

Values received via http post are null with AngularJS and Web api 2

I followed a tutorial and wanted to expand the functionality of already existing code. Code: https://send.firefox.com/download/27d75a7398f351c9/#wKkjkAuvlpBVOMKx9szFHA
It's using angularJS as the frontend and webapi 2 aspnet with entitiyframework. The problem is that my http posts are sending null values. I am guessing I have to post it in the right format, but im not sure how exactly to do it.
I tried transforming it into an object but it still received as null.
controller.js
function save(contact) {
var deferred = $q.defer();
$http.post('/api/Contact/' + contact).success(function (results) {
$scope.contact = results;
deferred.resolve(results);
}).error(function (data, status, headers, config) {
deferred.reject('Failed saving contact');
});
return deferred.promise;
};
fails at db.Contacts.Add(Contact); (null error)
public HttpResponseMessage Post([FromBody] Contact Contact)
{
if (ModelState.IsValid)
{
Console.Write("post contact");
Console.Write(Contact);
db.Contacts.Add(Contact);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, Contact);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = Contact.Id }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
Tried sending this:
{Name: "test", Address: "test", City: "teee", Country: "tesd"}
Edit:
After trying to save the contact with the save function:
output of console log
Request URL: http://localhost:64158/api/Contact/[object%20Object]
If i open the [object%20Object] in a new tab from the network view i get this:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'SampleEF6.Models.Contact Get(Int32)' in 'SampleEF6.Controllers.ContactController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
You're sending the data wrong. You're supposed to send the data (contact in this example) in the body of the request, instead of the url.
Try $http.post('/api/Contact/', contact)
https://docs.angularjs.org/api/ng/service/$http#post

can't call a function and pass a var using mvc

I am new to MVC, I looked at other solutions to my problem on web but still I can't find what is wrong with my code, I'm using code (as is) from umbraco website, I'm trying to call a function and pass a var from js, I don't understand what is the problem..., tried to solve it with online examples but getting the same error... help
//c#
public class MokedLoginController : SurfaceController
{
[HttpGet]
[Route("umbraco/surface/MokedLogin/DoLogin/{id}")]
public void DoLogin([FromBody]int member)
{
var _member = Services.MemberService.GetById(member);
if (_member != null)
FormsAuthentication.SetAuthCookie(_member.Username, false);
}
}
//js
angular.module('umbraco').controller('MokedLoginController', [
'$scope',
'$http',
'editorState',
'contentResource',
function ($scope, $http, editorState, contentResource) {
// Check if you are creating a new member
$scope.isNew = editorState.current.id <= 0;
// Define the login as member function
$scope.loginAsMember = function () {
// ### Setup cookie ????
var url = '/umbraco/surface/MokedLogin/DoLogin/{id}';
// Get the current member id using the editorState
var _memberId = editorState.current.id;
// Do Login
$http.post(
url, _memberId
).then(
function (response) {
// ### Redirect ????
// Get the redirect page from config
var urlPageRedirect = $scope.model.config.memberRedirectPage;
// Check if page is set in the config
if (urlPageRedirect)
{
contentResource.getNiceUrl(urlPageRedirect).then(function (data) {
window.open(data, '_blank') // Get the first url
});
} else {
// Open the root page
window.open('/', '_blank');
}
},
function (error) {
console.log(error.data);
}
);
};
}
]);
// Do Login
$http.post(
// the famouse exception that comes from ? and why ?
System.ArgumentException: The parameters dictionary contains a null entry for parameter 'member' of non-nullable type 'System.Int32' for method 'Void DoLogin(Int32)'
in 'ThePoolInsurance.Web.Controllers.MokedLoginController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

Sending message from server to specific client is not working using SignalR 2 and MVC 4.0

I wanted to call notify specific client from server using signalR but it was not working. my code was executed successfully but client dose not receive any call from server.
However this is working for all client.
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProcessStatusNotifyHub>();
hubContext.Clients.All.notify("Got it!");
But this is not working for specific client
[Updated Code]
Following code written in chat.cshtml
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.processStatusNotifyHub;//chatHub;
chat.client.notify = function (msg) {
alert(msg);
}
// Start the connection.
$.connection.hub.start().done(function () {
var myClientId = $.connection.hub.id;
console.log('connected: ' + myClientId);
$('#sendmessageToClient').click(function () {
//chat.server.send('imdadhusen', 'This is test text');
$.ajax({
url: '#Url.Action("Send", "PushNotification")',
type: 'POST',
data: { 'clientID': myClientId },
dataType: 'json',
success: function (result) {
alert(result.status);
}
});
});
});
});
Following code is written in Controller
[HttpPost]
public ActionResult Send(string clientID)
{
var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProcessStatusNotifyHub>();
//hubContext.Clients.All.notify("Got it!");
hubContext.Clients.User(clientID).notify("Got it!");
responseResult result = new responseResult();
result.status = "OK";
result.message = "Notification sent successfully";
return Json(result, JsonRequestBehavior.AllowGet);
}
I have tried debug the code it is showing correct value of client id on .cstml or controlloer. e.g. clientid : 0fdf6cad-b9c1-409e-8eb7-0a57c1cfb3be
Could you please help me to send notification to specific client from server.
The operation hubContext.Clients.User(string) is expecting the User ID of the current HTTP request, not SignalR's client ID.
If you want to use client ID use this operation:
hubContext.Clients.Client( )
If you want to access it by the current user, then you can get current user ID with this
string UserID=User.Identity.GetUserId()
This is not an answer to your specific question, but instead a suggestion on your code. Why not have the client use the Signalr connection to call the server? Just define a method in the hub that a client can call. Then in that method use the HubCallerContext to get the id.
This page shows you how to call the server from the client:
http://www.asp.net/signalr/overview/guide-to-the-api/hubs-api-guide-javascript-client
Then in the hub's method:
Clients.User(Context.ConnectionId).notify("Got it!");

Passing 2 parameters to $http.post return error 404

I am trying to pass 2 value to the function in RestAPI through $http.post method when the $http.post method is called browser console shows error
http://localhost:8550/api/Servicesapi/UpdateEmployeeServices/ 404 (Not Found)
But when i pass single value function executes successfully and no error is shown
here is my Angular Code
var servicedata = JSON.stringify($scope.services);
var sdata = { id: Id, services: servicedata };
$http.post('/api/Servicesapi/UpdateEmployeeServices', sdata)
.then(function (result) {
//Success
}, function() {
//Error
});
Here is API Function
[AcceptVerbs,HttpPost]
public void UpdateEmployeeServices(string id,Service[] services)
{
//some Implementation
}
I think your solution is(based on a major asumption that your route is actually UpdateEmployeeSrvices/<id>):
//var servicedata = JSON.stringify($scope.services);
//var sdata = { id: Id, services: servicedata };
$http.post('/api/Servicesapi/UpdateEmployeeServices/'+ Id , $scope.services)
.then(function (result) {
//Success
}, function() {
//Error
})

Categories