401 error calling REST service from mvc controller - asp.net-mvc

I am trying to make a request to a REST method and recieve the data in XML but this all goes well but when i want to use credentials for a method, because for this method you need to give credentials.
https://handshake:16a144bc5f480692d5c8d926068d2db5#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=236750347X6d2ee7
But when i use this one in the browser it work but this is not working from my controller.
//
// GET: /Home/Succes
public ActionResult Succes(string orderId)
{
string token = PaymentCalls.Login();
ViewBag.Token = token;
string _URL = "https://handshake:" + token + "#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=" + orderId;
NetworkCredential cr = new NetworkCredential("handshake", token);
XDocument doc = XDocument.Load(_URL);
var output = from feed in doc.Descendants("data")
select new Status
{
amount = feed.Element("amount").Value,
consumerAccountNumber = feed.Element("consumerAccountNumber").Value,
consumerCity = feed.Element("consumerCity").Value,
consumerEmail = feed.Element("consumerEmail").Value,
consumerName = feed.Element("consumerName").Value,
consumerZipcode = feed.Element("consumerZipcode").Value,
countryCode = feed.Element("countrCode").Value,
entranceCode = feed.Element("entranceCode").Value,
ipAddress = feed.Element("ipAddress").Value,
orderId = feed.Element("orderId").Value,
statsAdded = feed.Element("statsAdded").Value,
paymentSessionId = feed.Element("paymentSessionId").Value,
result = feed.Element("result").Value,
statusAction = feed.Element("statusAction").Value
};
return View(output);
So when we call this controller we get an 401 error but using the same url in the browser works. So i dont know but how can i set to pass credentials or something?

Related

Bad request when posting to OData Data Entity in Dynamics 365

I've created a public Data Entity in dynamics with the following fields:
I keep getting a bad request response, but I'm not sure why.
I've tried to make a POST request in two ways:
1.
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionStatus = "Created" };
string jsonMessage = JsonConvert.SerializeObject(hireAction);
using (HttpClient client = new HttpClient())
{
HttpRequestMessage requestMessage = new
HttpRequestMessage(HttpMethod.Post, "MyDynamicsEnvironmentName/data/HireActions?cross-company=true");
requestMessage.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
requestMessage.Headers.Add("Authorization", AuthResult.AuthorizationHeader);
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
if (response.StatusCode == System.Net.HttpStatusCode.OK)
{
//Logic
}
}
var url = "MyDynamicsEnvironmentName/data/HireActions?cross-company=true";
var req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentType = "application/json";
req.Headers["Authorization"] = AuthResult.AuthorizationHeader;
HireAction hireAction = new HireAction() { CompanyName = "DEMF", MovieId = "DEMF-000000014", HireActionId = "12345", HireActionStatus = "Created" };
var jsonSettings = new JsonSerializerSettings
{
DateTimeZoneHandling = DateTimeZoneHandling.Local
};
var postString = "CompanyName='DEMF'" + "&MovieId='DEMF-000000014'" + "&HireActionId=132&HireActionStatus='Created'";
var data = JsonConvert.SerializeObject(postString, jsonSettings);
var bytes = Encoding.Default.GetBytes(postString);
var newStream = req.GetRequestStream();
newStream.Write(bytes, 0, bytes.Length);
newStream.Close();
using (var resp = req.GetResponse())
{
var results = new StreamReader(resp.GetResponseStream()).ReadToEnd();
}
Some keypoints:
-Of course you'd replace MyDynamicsEnvironmentName with the URL for the environment. The URL is correct and verified however, by the fact that GET requests do work
-The Authresult.AuthorizationHeader contains a valid token, also validated by working GET requests
As said before, both of these result in a bad request. Does someone know what is wrong or missing?

Chained payments with permissions 520003 Authentication failed

I have problem with executing chained payment after obtaining permission from user. I have no troubles to get Access Token and Access Token Secret.
The code should work this way: User (personal type sandbox account) authorizes primary receiver (business type sandbox account) to take money from his account.
Primary receiver sends a part of the sum to the second receiver.
The code is written in ASP.NET MVC but I suppose it has nothing to do with the framework, I'm using PayPalAdaptivePaymentsSDK and PayPalPermissionsSDK
I want to use it in sandbox environment for testing.
I assume it has something to do with application id, I would be very grateful for step-by-step explanation
Here's how I obtain all my credentials:
I login into my developer account.
account1.Username, account1.Password, account1.Signature
- sandbox -> accounts -> I select primary receiver of the payment (business type account) -> API Credentials
applicationId - "APP-80W284485P519543T"
In the config file I specified mode as "sandbox".
I use the same config for executing the payment.
Then I want to execute following code and in payResponse I get errorId 520003 "Authentication failed. API credentials are incorrect."
public class PermissionController : Controller
{
private AdaptivePaymentsService _adaptivePaymentService;
public ActionResult Index()
{
ViewBag.AccessToken = PayPalConfig.AccessToken;
ViewBag.AccessTokenSecret = PayPalConfig.AccessTokenSecret;
return View();
}
public PermissionController()
{
_adaptivePaymentService = new AdaptivePaymentsService(PayPalConfig.GetConfig());
}
public ActionResult GetPermission()
{
RequestPermissionsRequest rp = new RequestPermissionsRequest();
rp.scope = new List<string>();
rp.scope.Add("EXPRESS_CHECKOUT");
Dictionary<string, string> config = PayPalConfig.GetConfig();
rp.callback = "http://localhost:42072/Permission/GetAccessToken";
rp.requestEnvelope = new PayPal.Permissions.Model.RequestEnvelope("en_US");
RequestPermissionsResponse rpr = null;
PermissionsService service = new PermissionsService(config);
rpr = service.RequestPermissions(rp);
string confirmPermissions = "https://www.sandbox.paypal.com/webscr&cmd=_grant-permission&request_token=" + rpr.token;
return Redirect(confirmPermissions);
}
public ActionResult GetAccessToken()
{
Uri uri = Request.Url;
Dictionary<string, string> config = PayPalConfig.GetConfig();
var gat = new GetAccessTokenRequest();
gat.token = HttpUtility.ParseQueryString(uri.Query).Get("request_token");
gat.verifier = HttpUtility.ParseQueryString(uri.Query).Get("verification_code");
gat.requestEnvelope = new PayPal.Permissions.Model.RequestEnvelope("en_US");
GetAccessTokenResponse gats = null;
var service = new PermissionsService(config);
gats = service.GetAccessToken(gat);
_adaptivePaymentService.SetAccessToken(gats.token);
_adaptivePaymentService.SetAccessTokenSecret(gats.tokenSecret);
PayPalConfig.AccessToken = _adaptivePaymentService.getAccessToken();
PayPalConfig.AccessTokenSecret = _adaptivePaymentService.getAccessTokenSecret();
return RedirectToAction("Index");
}
public ActionResult ChainedPayment()
{
ReceiverList receiverList = new ReceiverList();
receiverList.receiver = new List<Receiver>();
Receiver secondaryReceiver = new Receiver(1.00M);
secondaryReceiver.email = "mizerykordia6662-facilitator#gmail.com";
receiverList.receiver.Add(secondaryReceiver);
Receiver primaryReceiver = new Receiver(5.00M);
primaryReceiver.email = "mizTestMerchant#test.com";
primaryReceiver.primary = true;
receiverList.receiver.Add(primaryReceiver);
PayPal.AdaptivePayments.Model.RequestEnvelope requestEnvelope = new PayPal.AdaptivePayments.Model.RequestEnvelope("en_US");
string actionType = "PAY";
string returnUrl = "http://localhost:42072/Home/Index";
string cancelUrl = "https://devtools-paypal.com/guide/ap_chained_payment/dotnet?cancel=true";
string currencyCode = "USD";
_adaptivePaymentService.SetAccessToken(PayPalConfig.AccessToken);
_adaptivePaymentService.SetAccessTokenSecret(PayPalConfig.AccessTokenSecret);
PayRequest payRequest = new PayRequest(requestEnvelope, actionType,
cancelUrl, currencyCode, receiverList, returnUrl);
// it breaks here
PayResponse payResponse = _adaptivePaymentService.Pay(payRequest);
PaymentDetailsRequest paymentDetailsRequest = new PaymentDetailsRequest(new PayPal.AdaptivePayments.Model.RequestEnvelope("en-US"));
paymentDetailsRequest.payKey = payResponse.payKey;
SetPaymentOptionsRequest paymentOptions = new SetPaymentOptionsRequest()
{ payKey = payResponse.payKey };
_adaptivePaymentService.SetPaymentOptions(paymentOptions);
PaymentDetailsResponse paymentDetailsRespons = _adaptivePaymentService.PaymentDetails(paymentDetailsRequest);
ExecutePaymentRequest exec = new ExecutePaymentRequest(new PayPal.AdaptivePayments.Model.RequestEnvelope("en-US"), paymentDetailsRequest.payKey);
ExecutePaymentResponse response = _adaptivePaymentService.ExecutePayment(exec);
return RedirectToAction("Index");
}
}

How to handle error scenarios in Csv file download with web api

I am using the following code to post data to my api controller
var form = document.createElement('form');
form.action = '/api/reportsapi/exportToCsv';
form.method = 'POST';
form.style.display = 'none';
for (i in data) {
if (data[i] != "") {
var inputElement = document.createElement('textarea');
inputElement.name = i;
inputElement.value = data[i];
form.appendChild(inputElement);
}
}
document.body.appendChild(form);
form.submit();
and my api controller returns a HttpResponseMessage
var csvValidRequestResult = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(csvReport.Data) };
csvValidRequestResult.Content.Headers.ContentType = new MediaTypeHeaderValue("text/comma-separated-values");
csvValidRequestResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = csvReport.FileName };
return csvValidRequestResult;
all this works fine. A file with data is downloaded when the above scripts hits the controller.
But the problem arises if there is any server side exception, in that case the page gets redirected to the the form's api url.
Is there something I can do to get to know of the error and act accordingly on the client side ?

Retrieving OAuth Verification Code via .NET HttpWebRequest

I'm attempting to replicate the OAuth steps normally done via the "Connect to QuickBooks" button using HttpWebRequest/HttpWebResponse.
It's easy at first grabbing the request token and generating the authorization link:
private const string oauthBaseUrl = "https://oauth.intuit.com/oauth/v1";
private const string urlRequestToken = "/get_request_token";
private const string urlAccessToken = "/get_access_token";
private const string verifyUrl = "https://appcenter.intuit.com";
private const string authorizeUrl = "https://appcenter.intuit.com/Connect/Begin";
...
var consumerContext = new OAuthConsumerContext
{
ConsumerKey = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(ckSS),
ConsumerSecret = System.Utilities.Cryptography.Encryption.ConvertToUnsecureString(csSS),
SignatureMethod = SignatureMethod.HmacSha1
};
IOAuthSession session = new OAuthSession(consumerContext, oauthBaseUrl + urlRequestToken, authorizeUrl, oauthBaseUrl + urlAccessToken);
IToken requestToken = session.GetRequestToken();
string authorizationLink = session.GetUserAuthorizationUrlForToken(requestToken, callbackUrl);
Then I walk through grabbing the request verification code that is generated in the set-cookie string when requesting the site at the authorization link:
var requestAuth = (HttpWebRequest) WebRequest.Create(authorizationLink);
requestAuth.Method = "GET";
requestAuth.ContentType = "application/x-www-form-urlencoded";
requestAuth.Accept = "text/html, application/xhtml+xml, */*";
requestAuth.Headers.Add("Accept-Encoding", "gzip, deflate");
requestAuth.Headers.Add("Accept-Language", "en-us");
requestAuth.Host = "appcenter.intuit.com";
requestAuth.KeepAlive = true;
var responseAuth = (HttpWebResponse) requestAuth.GetResponse();
Stream answerAuth = responseAuth.GetResponseStream();
var _answerAuth = new StreamReader(answerAuth);
string htmlAuth = _answerAuth.ReadToEnd();
// Need to grab the request verification code embedded in the set-cookie string
string cookies = responseAuth.Headers.Get("Set-Cookie");
int idx = cookies.IndexOf("__RequestVerificationToken", StringComparison.Ordinal);
if (idx > 0)
{
int startIndex = cookies.IndexOf("=", idx, StringComparison.InvariantCultureIgnoreCase);
int endIndex = cookies.IndexOf(";", startIndex + 1, StringComparison.InvariantCultureIgnoreCase);
requestVerificationCode = cookies.Substring(startIndex + 1, endIndex - (startIndex + 1));
postDataString += requestVerificationCode;
}
As I understand it, the request verification code is needed in order to get the OAuth verification code that is returned in the postdata appended to the callback URL, which is in turn needed to get the access token.
This is where the difficulty begins. Using Fiddler2, I find that the login URL for generating the OAuth verification code is https://appcenter.intuit.com/Account/LogOnJson. But no matter how much I try to replicate the HTTP POST using HttpWebRequest, all I get in return is a 500 error. I'm wondering if anyone has a working example of this step? Is this even possible? I hope so, because the alternative of pulling up IE and walking through the same steps like a macro is too ugly.
Any help on this? Thanks!
You can download the dotnet sample app for understanding how the OAUTH flow works:
https://github.com/IntuitDeveloperRelations/IPP_Sample_Code
Set your app keys in web.config.

400 Bad Request in Rest WCF Post method?

My Code is :
[WebInvoke(ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml, UriTemplate = "InsertUser", Method = "POST")]
public int InsertUser(Sales_Data instance)
{
using (DataEntities cxt = new DataEntities())
{
Sales_Data visitor = new Sales_Data();
visitor.fname = instance.fname;
visitor.email = instance.email;
visitor.phone = instance.phone;
cxt.AddToSales_Data(visitor);
cxt.SaveChanges();
return visitor.ID;
}
}
Request Input :
<Sales_Data>
<fname>ff</fname>
<email>ggg</email>
<phone>4444</phone>
</Sales_Data>
Then while testing it in rest client i am getting 400 Bad Request.
Can you please any thing wrong in Request input .

Resources