"CSRF Validation failed" when invoking SaveChanges ODataClient method in ASP.NET - c#

I am trying to implement a code to modify entities through WCF Dataservices from the OData client I have generated. I have followed the same principle that was implemented in this link - https://msdn.microsoft.com/en-us/library/dd756368(v=vs.110).aspx
I am getting "CSRF token validation failed" error during the SaveChanges method call. Please see code below:
// Define the URI of the public Northwind OData service.
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Uri cuanUri =
new Uri("https://xxxx.xxxx.com:44300/sap/opu/odata/sap/CUAN_IMPORT_SRV/",
UriKind.Absolute);
// Create a new instance of the typed DataServiceContext.
DateTime stimestamp = new DateTime();
DateTime dob = new DateTime(1992,05,02);
CUAN_IMPORT_SRV_Entities context = new CUAN_IMPORT_SRV_Entities(cuanUri);
context.SendingRequest2 += SendBaseAuthCredsOnTheRequest;
Contact newContact = Contact.CreateContact("C160717055735", "SAP_ODATA_IMPORT", stimestamp);
//Product newProduct = Product.CreateProduct(0, "White Tea - loose", false);
newContact.CompanyId = "BLUEFIN1";
newContact.CompanyIdOrigin = "SAP_ODATA_IMPORT";
newContact.CountryDescription = "Singapore";
newContact.DateOfBirth = dob;
newContact.EMailAddress = "j_prado#yahoo.com";
newContact.EMailOptIn = "Y";
newContact.FirstName = "Jeffrey1";
newContact.FunctionDescription = "Consultant";
newContact.GenderDescription = "Male";
newContact.LastName = "Prado1";
newContact.PhoneNumber = "+6596492714";
newContact.PhoneOptin = "Y";
Company newCompany = Company.CreateCompany("BLUEFIN1", "SAP_ODATA_IMPORT", stimestamp);
newCompany.IndustryDescription = "1007";
newCompany.CompanyName = "BLUEFIN1";
Interaction newInteraction = Interaction.CreateInteraction("");
newInteraction.CommunicationMedium = "WEB";
newInteraction.ContactId = "C160717055735";
newInteraction.ContactIdOrigin = "SAP_ODATA_IMPORT";
newInteraction.InteractionType = "WEBSITE_REGISTRATION";
newInteraction.Timestamp = stimestamp;
ImportHeader newHeader = ImportHeader.CreateImportHeader("");
newHeader.Timestamp = stimestamp;
newHeader.UserName = "ENG";
newHeader.SourceSystemType = "EXT";
newHeader.SourceSystemId = "HYBRIS";
try
{
// Add the new entities to the CUAN entity sets.
context.AddToImportHeaders(newHeader);
context.AddToContacts(newContact);
context.AddToCompanies(newCompany);
context.AddToInteractions(newInteraction);
// Send the insert to the data service.
DataServiceResponse response = context.SaveChanges();
// Enumerate the returned responses.
foreach (ChangeOperationResponse change in response)
{
// Get the descriptor for the entity.
EntityDescriptor descriptor = change.Descriptor as EntityDescriptor;
if (descriptor != null)
{
Contact addedContact = descriptor.Entity as Contact;
if (addedContact != null)
{
Console.WriteLine("New contact added with ID {0}.",
addedContact.CompanyId);
}
}
}
}
catch (DataServiceRequestException ex)
{
throw new ApplicationException(
"An error occurred when saving changes.", ex);
}
}
private static void SendBaseAuthCredsOnTheRequest(object sender,
SendingRequest2EventArgs e)
{
var authHeaderValue = Convert.ToBase64String(Encoding.ASCII.GetBytes(String.Format("{0}:{1}"
, "XXXXX", "XXXXX")));
e.RequestMessage.SetHeader("Authorization", "Basic " + authHeaderValue); //this is where you pass the creds.
}
The code above fails when invoking: DataServiceResponse response = context.SaveChanges();

Related

C# Authorize.net Create Profile Issue

The following code is charging the card, however it is not creating the profile....any tips? I'm assuming I'm missing something, or using the wrong Type...
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = userID.ToString()
},
profile = new customerProfilePaymentType()
{
createProfile = true
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
UPDATE:
Since apparently OpaqueData is not allowed, I changed it to make the profile manually. I am getting the following Error: "Error: I00001 Successful."
// Add Payment method to Customer.
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
var request2 = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = userID.ToString()
};
var controller2 = new createCustomerPaymentProfileController(request2);
controller2.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse response2 = controller2.GetApiResponse();
if (response2 != null && response2.messages.resultCode == messageTypeEnum.Ok)
{
if (response2 != null && response2.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
Utility.AppendTextToFile("Error: " + response.messages.message[0].code + " " + response.messages.message[0].text, Server.MapPath("/pub/auth.txt"));
}
Update #2
Very confused as auth.net documentation says this code means success...so why don't I see the CIM payment method created??? RESPONSE CODE DOCS
Update #3
So I was printing out the main response message instead of the CIM request message, duh. The actual error was: "E00114 Invalid OTS Token."
Based on the the documentation, that error is usually from a used Key, so I am now generating 2 keys (One to process and One to store via CIM) but am now getting this error: "E00040 The record cannot be found."....Any ideas?
So the answer to this question is:
You can not auto create a payment profile using opaque card data, so the answer is to make it manually once you have a successful charge.
You can not use the same opaque card data to charge and store, as they are one time use, so for my web method I ended up passing 2 opaque data keys.
You have to make different calls for setting up a brand new customer and an existing customer just adding a new card. I have pasted an excerpt of my end solution below:
ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? AuthorizeNet.Environment.PRODUCTION : AuthorizeNet.Environment.SANDBOX);
// define the merchant information (authentication / transaction id)
ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = new merchantAuthenticationType()
{
name = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-LoginID-SandBox"]),
ItemElementName = ItemChoiceType.transactionKey,
Item = (System.Configuration.ConfigurationManager.AppSettings["Authorize-Live"].ToUpper() == "TRUE" ? System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey"] : System.Configuration.ConfigurationManager.AppSettings["Authorize-TransactionKey-SandBox"])
};
if (paymentNonce.Trim() != "")
{
//set up data based on transaction
var opaqueData = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce };
//standard api call to retrieve response
var paymentType = new paymentType { Item = opaqueData };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), // authorize and capture transaction
amount = paymentAmount,
payment = paymentType,
customer = new customerDataType()
{
type = customerTypeEnum.individual,
id = "YOUR_DB_USERID"
},
profile = new customerProfilePaymentType()
{
createProfile = false
}
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the contoller that will call the service
var controller = new createTransactionController(request);
const SslProtocols _Tls12 = (SslProtocols)0x00000C00;
const SecurityProtocolType Tls12 = (SecurityProtocolType)_Tls12;
ServicePointManager.SecurityProtocol = Tls12;
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
string merchID = "STORED AUTHORIZE.NET CUSTOMERID, return blank string if none!";
var opaqueData2 = new opaqueDataType { dataDescriptor = "COMMON.ACCEPT.INAPP.PAYMENT", dataValue = paymentNonce2 };
//standard api call to retrieve response
var paymentType2 = new paymentType { Item = opaqueData2 };
customerPaymentProfileType opaquePaymentProfile = new customerPaymentProfileType();
opaquePaymentProfile.payment = paymentType2;
opaquePaymentProfile.customerType = customerTypeEnum.individual;
if (merchID == "")
{
// CREATE NEW AUTH.NET AIM CUSTOMER
List<customerPaymentProfileType> paymentProfileList = new List<customerPaymentProfileType>();
paymentProfileList.Add(opaquePaymentProfile);
customerProfileType customerProfile = new customerProfileType();
customerProfile.merchantCustomerId = "YOUR_DB_USERID";
customerProfile.paymentProfiles = paymentProfileList.ToArray();
var cimRequest = new createCustomerProfileRequest { profile = customerProfile, validationMode = validationModeEnum.none };
var cimController = new createCustomerProfileController(cimRequest); // instantiate the contoller that will call the service
cimController.Execute();
createCustomerProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
// STORE cimResponse.customerProfileId IN DATABASE FOR USER
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("New Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
else
{
// ADD PAYMENT PROFILE TO EXISTING AUTH.NET AIM CUSTOMER
var cimRequest = new createCustomerPaymentProfileRequest
{
paymentProfile = opaquePaymentProfile,
validationMode = validationModeEnum.none,
customerProfileId = merchID.Trim()
};
var cimController = new createCustomerPaymentProfileController(cimRequest);
cimController.Execute();
//Send Request to EndPoint
createCustomerPaymentProfileResponse cimResponse = cimController.GetApiResponse();
if (cimResponse != null && cimResponse.messages.resultCode == messageTypeEnum.Ok)
{
if (cimResponse != null && cimResponse.messages.message != null)
{
//Console.WriteLine("Success, createCustomerPaymentProfileID : " + response.customerPaymentProfileId);
}
}
else
{
for (int i = 0; i < cimResponse.messages.message.Length; i++)
Utility.AppendTextToFile("Add Error (" + merchID + ") #" + i.ToString() + ": " + cimResponse.messages.message[i].code + " " + cimResponse.messages.message[i].text, Server.MapPath("/pub/auth.txt"));
}
}
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}
else
{
// RUN PAYMENT WITH STORED PAYMENT PROFILE ID
customerProfilePaymentType profileToCharge = new customerProfilePaymentType();
profileToCharge.customerProfileId = CustomerID;
profileToCharge.paymentProfile = new paymentProfile { paymentProfileId = PaymentID };
var transactionRequest = new transactionRequestType
{
transactionType = transactionTypeEnum.authCaptureTransaction.ToString(),
amount = paymentAmount,
profile = profileToCharge
};
var request = new createTransactionRequest { transactionRequest = transactionRequest };
// instantiate the collector that will call the service
var controller = new createTransactionController(request);
controller.Execute();
// get the response from the service (errors contained if any)
var response = controller.GetApiResponse();
//validate
if (response != null)
{
if (response.messages.resultCode == messageTypeEnum.Ok)
{
if (response.transactionResponse.messages != null)
{
responseData.Success = true;
transactionID = response.transactionResponse.transId;
}
else
{
responseData.Message = "Card Declined";
responseData.Success = false;
if (response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
}
}
else
{
responseData.Message = "Failed Transaction";
responseData.Success = false;
if (response.transactionResponse != null && response.transactionResponse.errors != null)
{
responseData.Message = response.transactionResponse.errors[0].errorText;
}
else
{
responseData.Message = response.messages.message[0].text;
}
}
}
else
{
responseData.Message = "Failed Transaction, Try Again!";
responseData.Success = false;
}
}

To know reason of not added record in NetSuite

Trying to add new customer to NetSuite like it described in sample in manual.
private static void Main(string[] args)
{
ApplicationInfo _appInfo;
var service = new NetSuiteService();
service.CookieContainer = new CookieContainer();
_appInfo = new ApplicationInfo();
_appInfo.applicationId = "FB31C4F2-CA6C-4E5F-6B43-57632594F96";
service.applicationInfo = _appInfo;
var passport = new Passport();
passport.account = "5920356_SB9";
passport.email = "a#a.com";
var role = new RecordRef();
role.internalId = "3";
passport.role = role;
passport.password = "#sdkkr_5543";
try
{
var status = service.login(passport).status;
}
catch (Exception e)
{
Console.Out.WriteLine(e.Message);
throw;
}
var cust = new Customer();
cust.entityId = "XYZ Inc";
cust.altEmail = "aaa#aaa.aaa";
var response = service.add(cust);
Console.Out.WriteLine("response.status.isSuccess " + response.status.isSuccess) ;
Console.Out.WriteLine("response.status.isSuccessSpecified " + response.status.isSuccessSpecified);
service.logout();
}
As result I got:
response.status.isSuccess False
response.status.isSuccessSpecified True
I suppose customer was not inserted. What is wrong and how to know that?
When you call add() on the service, the response contains a status property which contains a statusDetail property. statusDetail is an array of the messages (warnings and errors) that resulted from your add(). You can loop through these to find out why saving your customer record was unsuccessful:
var response = service.add(cust);
if (!response.status.isSuccess)
{
foreach (var error in response.status.statusDetail)
{
Console.WriteLine($"Error creating customer: {error.type} {error.message}");
}
}

Linkedin api post not work?

public ActionResult AuthorizeLinkedin(string code, string state, string error, string error_description)
{
//Linkedin
if (!string.IsNullOrEmpty(error) || !string.IsNullOrEmpty(error_description))
{
// handle error and error_description
}
else
{
objusermodel = new UserModel();
var host = ExtractHost();
var _redirectUrl = Url.Action("AuthorizeLinkedin", "Investments", null, Request.Url.Scheme, host);
var userToken = api.OAuth2.GetAccessToken(code, _redirectUrl);
// keep this token for your API requests
var user = new UserAuthorization(userToken.AccessToken);
var fields = FieldSelector.For().WithFirstName().WithFollowing();
if (Session["ShareResponse"] != null)
{
shareResponse = Session.GetObjectFromJson("ShareResponse");
}
//try
//{
var profile = api.Profiles.GetMyProfile(user, new string[] { "en-US" }, fields);
api.Social.Post(user, new PostShare()
{
Content = new PostShareContent()
{
Title = "FUNDING PORTAL",
Description = shareResponse.Message,
SubmittedUrl = shareResponse.ShareUrl,
SubmittedImageUrl = shareResponse.ImageUrl,
},
Visibility = new Visibility()
{
Code = "anyone"
},
});
shareResponse.Success = 1;
shareResponse.flag = true;
Session.SetObjectAsJson("ShareResponse", shareResponse);
TempData["PromoboxFN"] = shareResponse.ImageUrl;
TempData.Keep("PromoboxFN");
return Redirect(shareResponse.RedirectUrl);
//}
//catch (Exception ex)
//{
// throw;
// shareResponse.Success = 0;
// shareResponse.flag = true;
// Session.SetObjectAsJson("ShareResponse", shareResponse);
// return Redirect(shareResponse.RedirectUrl);
//}
}
return null;
}
Give the error:
"api.Social.Post(user, new PostShare()" to this point An exception of
type 'Sparkle.LinkedInNET.LinkedInApiException' occurred in
Sparkle.LinkedInNET.dll but was not handled in user code
Additional information: API error (500) Internal service error at https://api.linkedin.com/v1/people/~/shares

ASP.NET stripe.net Cannot charge a customer that has no active card

protected void ChargePayment(object sender, EventArgs e)
{
StripeCustomer CurrentCustomer = GetCustomer();
if (CurrentCustomer == null)
{
return;
}
var myCharge = new StripeChargeCreateOptions();
myCharge.Currency = "dkk";
myCharge.CustomerId = CurrentCustomer.Id;
myCharge.Description = "KPHF Prorated Charge";
string key = "sk_test_P6GjMq1OVwmxZv5YNozAX6dY";
var chargeService = new StripeChargeService(key);
try
{
chargeService.Create(myCharge);
}
catch (StripeException ex)
{
exError.Text = ex.Message;
}
}
private StripeCustomer GetCustomer()
{
MembershipUser CurrentUser = Membership.GetUser();
var myCustomer = new StripeCustomerCreateOptions();
var myCustomer2 = new StripeCreditCardOptions();
myCustomer.Email = cMail.Text;
myCustomer2.TokenId = CreditCard.Text;
myCustomer2.ExpirationMonth = CardMonth.SelectedItem.Text;
myCustomer2.ExpirationYear = CardYear.SelectedItem.Text;
myCustomer2.Cvc = cvc.Text;
myCustomer.PlanId = "1";
var customerService = new StripeCustomerService("sk_test_P6GjMq1OVwmxZv5YNozAX6dY");
try
{
StripeCustomer result = customerService.Create(myCustomer);
return result;
}
catch (StripeException ex)
{
exError.Text = ex.Message;
return null;
}
After entering credit card info I do get customer created in the stripe system, but he's not being charged and I get following exception: "Cannot charge a customer that has no active card". Any help or tips?
you are not attaching the card with the customer. You have created the card object but not attached with the customer. Follow this syntax to add the card
var myCustomer = new StripeCustomerCreateOptions();
myCustomer.Email = "pork#email.com";
myCustomer.Description = "Johnny Tenderloin (pork#email.com)";
// setting up the card
myCustomer.SourceCard = new SourceCard()
{
Number = "4242424242424242",
ExpirationYear = "2022",
ExpirationMonth = "10",
Cvc = "1223" // optional
};
myCustomer.PlanId = *planId*; // only if you have a plan
myCustomer.TaxPercent = 20; // only if you are passing a plan, this tax percent will be added to the price.
myCustomer.Coupon = *couponId*; // only if you have a coupon
myCustomer.TrialEnd = DateTime.UtcNow.AddMonths(1); // when the customers trial ends (overrides the plan if applicable)
myCustomer.Quantity = 1; // optional, defaults to 1
var customerService = new StripeCustomerService();
StripeCustomer stripeCustomer = customerService.Create(myCustomer)
you can read more about it here stripe .net

Controller is returning blank View in my website

public async Task<IActionResult> Contact1()
{
if (Convert.ToBoolean(HttpContext.Session.GetString("login")))
{
var pass = new ContactViewModel();
var username = HttpContext.Session.GetString("username");
Program.readname(HttpContext.Session.GetString("username"));
var names = HttpContext.Session.GetString("studentnames");
var obj1 = JsonConvert.DeserializeObject<Program.Data>(names);
if (Program.datecheck(username, DateTime.Today.Date))
{
try{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
}
catch(Exception ee)
{ ViewBag.m6 = ee.Message; ViewBag.attendance = "Attendace is not take yet";}
}
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
pass.studentname = obj1.studentname1;
pass.studentrollno = obj1.studentrollno1;
pass.date = DateTime.Today.Date;
HttpContext.Session.SetInt32("classselect", 1);
ViewData["Message"] = "Student Attendance of Class: " + HttpContext.Session.GetString("classname1");
ViewBag.Login = HttpContext.Session.GetString("login");
ViewBag.name = HttpContext.Session.GetString("name");
ViewBag.classname1 = HttpContext.Session.GetString("classname1");
ViewBag.classname2 = HttpContext.Session.GetString("classname2");
ViewBag.classname3 = HttpContext.Session.GetString("classname3");
ViewBag.classname4 = HttpContext.Session.GetString("classname4");
return View("/Views/Home/Contact.cshtml", pass);
}
else
{
ViewData["Message"] = "Please Login First!!";
return View("/Views/Home/Login.cshtml");
}
}
The above code is runnig well in my local ISS server but when i run this on bluemix then i am getting blank page. I tried to find out the problem and get to the conclusion that if the control does not enter in the if part of that code:
if (Program.datecheck(username, DateTime.Today.Date))
{
var handler = new HttpClientHandler { Credentials = new NetworkCredential(user, password) };
using (var client = Program.CreateHttpClient(handler, user, database3))
{
string check = username + Convert.ToString(DateTime.Today.Date);
var readresponse = client.GetStringAsync(check).Result;
var obj2 = JsonConvert.DeserializeObject<Program.Data>(readresponse);
pass.studentattend = obj2.studentattend1;
}
}
else { ViewBag.attendance = "Attendace is not take yet"; }
then it will run fine.I am unable to find what is wrong in that query.

Categories

Resources