I'm using IPN Simulator to send the requests:
https://developer.paypal.com/developer/ipnSimulator
When I receive the IPN, I make a POST to paypal with the same data, adding &cmd=_notify-validate at the end. Problem is I always receive "INVALID" response. Is it because of IPN simulator or am I posting a wrong request ?
This is my IPN Controller:
[HttpPost]
public string IPN()
{
bool useSandbox = true;
StringBuilder to_send = new StringBuilder();
foreach (string key in Request.Form.Keys)
{
if (to_send.ToString().Equals(""))
to_send.AppendFormat("{0}={1}", key, Request.Form[key]);
else
to_send.AppendFormat("&{0}={1}", key, Request.Form[key]);
}
string paypalUrl = useSandbox ? "https://www.sandbox.paypal.com/cgi-bin/webscr"
: "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(paypalUrl);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
to_send.AppendFormat("&{0}={1}", "cmd", "_notify-validate");
string strRequest = to_send.ToString();
req.ContentLength = strRequest.Length;
string response = "";
using (StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII))
{
streamOut.Write(strRequest);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
}
Here's what I receive from paypal :
> payment_type: instant
payment_date: Sun Aug 09 2015 12:23:13 GMT+0300 (GTB Daylight Time)
payment_status: Completed
address_status: confirmed
payer_status: verified
first_name: John
last_name: Smith
payer_email: buyer#paypalsandbox.com
payer_id: TESTBUYERID01
address_name: John Smith
address_country: United States
address_country_code: US
address_zip: 95131
address_state: CA
address_city: San Jose
address_street: 123 any street
business: seller#paypalsandbox.com
receiver_email: seller#paypalsandbox.com
receiver_id: seller#paypalsandbox.com
residence_country: US
item_name: something
item_number: AK-1234
quantity: 1
shipping: 3.04
tax: 2.02
mc_currency: USD
mc_fee: 0.44
mc_gross: 12.34
mc_gross1: 12.34
txn_type: web_accept
txn_id: 363750782
notify_version: 2.1
custom: xyz123
invoice: abc1234
test_ipn: 1
verify_sign: AUxvCDK2PEEhNsHhVyUQ8Y-mDqfQARYxDdlEIxTy83GhdfASQp4iG0Rj
And here's what I'm posting back:
payment_type=instant&payment_date=Sun Aug 09 2015 12:23:13 GMT+0300 (GTB Daylight Time)&payment_status=Completed&address_status=confirmed&payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer#paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John Smith&address_country=United States&address_country_code=US&address_zip=95131&address_state=CA&address_city=San Jose&address_street=123 any street&business=seller#paypalsandbox.com&receiver_email=seller#paypalsandbox.com&receiver_id=seller#paypalsandbox.com&residence_country=US&item_name=something&item_number=AK-1234&quantity=1&shipping=3.04&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&txn_type=web_accept&txn_id=363750782¬ify_version=2.1&custom=xyz123&invoice=abc1234&test_ipn=1&verify_sign=AUxvCDK2PEEhNsHhVyUQ8Y-mDqfQARYxDdlEIxTy83GhdfASQp4iG0Rj&cmd=_notify-validate
Edit 1:
I tried changing the encoding to UTF-8 as it says on paypal documentation, but it still doesn't work :
Ensure that you use the same character encoding for your response string as the encoding specified in the charset field of the original IPN message. When testing using the IPN Simulator, the character encoding will always be UTF-8.
byte[] byteArray = Encoding.UTF8.GetBytes(strRequest);
string response = "";
using (BinaryWriter streamOut = new BinaryWriter(req.GetRequestStream(), System.Text.Encoding.UTF8))
{
streamOut.Write(byteArray, 0, byteArray.Length);
streamOut.Close();
using (StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream()))
{
response = streamIn.ReadToEnd();
}
}
Is it possible that the variables in Request.Form are not in the order they have been sent ?
cmd=_notify-validate is required to be preceding the original variables not succeeding them, you may want make some adjustment in your to_send StringBuilder code block to something like this:
StringBuilder to_send = new StringBuilder();
to_send.Append("cmd=_notify-validate");
foreach (string key in Request.Form.Keys)
{
to_send.AppendFormat("&{0}={1}", key, Request.Form[key]);
}
string strRequest = to_send.ToString();
p.s Refer here for IPN trouble shooting tips , this would be quite helpful as most of the issues have been covered in there
Related
I'm getting this error using the common EmailSender service with email address like test#pläne.de:
An unhandled exception occurred while processing the request.
SmtpException: Mailbox unavailable. The server response was: Requested action not taken: mailbox unavailable
System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, string response)
I tried with IdnMapping etc. but had no success. Has anybody had a similar issue and found a solution?
Code snippet:
public Task SendEmailAsync(string email, string subject, string htmlMessage)
{
var smtp = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build().GetSection("Smtp");
string fromMail = smtp["FromAddress"];
string fromPassword = smtp["Password"];
// string userName = smtp["UserName"];
MailMessage message = new MailMessage();
// idn mapping
IdnMapping idn = new IdnMapping();
message.From = new MailAddress(fromMail);
// message.From = new MailAddress(idn.GetAscii(fromMail));
message.Subject = subject;
message.To.Add(new MailAddress(email));
message.Body = "<html><body> " + htmlMessage + " </body></html>";
message.IsBodyHtml = true;
var smtpClient = new SmtpClient(smtp["Server"])
{
Port = Convert.ToInt32(smtp["Port"]),
//Credentials = new NetworkCredential(userName, fromPassword),
Credentials = new NetworkCredential(fromMail, fromPassword),
//Credentials = new NetworkCredential(idn.GetAscii(fromMail), fromPassword),
EnableSsl = true,
};
return smtpClient.SendMailAsync(message);
}
Thanks!
umlauts ä ü ö is an invalid character. And there doesn't seem to be a ready-made solution to this problem.
You can create some sort of translation table, for example:
ö = oe
ä = ae
ü = ue
Maybe this will help you solve the problem.
I'm trying to connect my asp.net REST api to salesforce. I'm succesfully going through authentification, but when I start to send POST requests, I'm getting an error
{"errorCode":"INVALID_SESSION_ID","message":"Session expired or invalid"}
Here is my POST request:
//SFServerUrl = "https://na17.salesforce.com/services/";
//url = "data/v28.0/sobjects/Account";
ASCIIEncoding ascii = new ASCIIEncoding();
byte[] postBytes = ascii.GetBytes(postBody);
HttpWebRequest request = WebRequest.Create(Globals.SFServerUrl + url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = postBytes.Length;
Stream postStream = request.GetRequestStream();
postStream.Write(postBytes, 0, postBytes.Length);
HttpCookie cookie = HttpContext.Current.Request.Cookies[Globals.SFCookie];
var ticket = FormsAuthentication.Decrypt(cookie.Value);
string authToken = ticket.UserData;
request.Headers.Add("Authorization", "Bearer " + authToken);
postStream.Close();
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;
do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);
return new Tuple<bool, string>(true, sb.ToString());
When I'm trying to send GET request - I recieve 200 response.
Also, I've tried to send a POST Request with the same token from Simple Rest Client and it get's 200 response. I tried to change my "Authorization : Bearer" Header to "Authorization : Oauth", but nothing changed. I also tried to catch this error, get refresh token and send a request again with refreshed token, but nothing changed. Please, help me with this.
Using workbench I was able to POST the following JSON to /services/data/v29.0/sobjects/Account and create a new Account.
{
"Name" : "Express Logistics and Transport"
}
Raw Response
HTTP/1.1 201 Created
Date: Sun, 07 Sep 2014 21:32:06 GMT
Set-Cookie: BrowserId=_HC-bzpTQABC1237vFu2hA;Path=/;Domain=.salesforce.com;Expires=Thu, 06-Nov-2014 21:32:06 GMT
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Sforce-Limit-Info: api-usage=209/15000
Location: /services/data/v29.0/sobjects/Account/0010000000000001AAA
Content-Type: application/json;charset=UTF-8
Content-Encoding: gzip
Transfer-Encoding: chunked
{
"id" : "0010000000000001AAA",
"success" : true,
"errors" : [ ]
}
Things to check:
Your URL. It appears to be missing the leading /services
Is SFServerUrl the same Salesforce pod/server that the Session Id was issued to? If the Session Id came from another pod then it would be invalid on na17.
How did you create the Session Id? If you used OAuth, what scopes did you request?
Is the Session Id coming out of the cookie valid?
Has something else using the same Session Id called logout and invalidated the session?
Incidentally, the Salesforce StackExchange site is a great place to ask Salesforce specific questions.
See also:
Using REST API Resources - Create a Record
The problem was that I added Headers after Content. When I switched these lines of code everything worked.
Is there any way to go to test Chargebacks/Disputes on the PayPal Sandbox test site?
I try to use the resolution center to create new cases both through the normal method of disputing a charge and through the sandbox specific "Create or Resolve Case" section of the Resolution Center.
Either way I do it, I can only ever get the disputes into a status of "Being Reviewed By PayPal". No IPN notifications are sent out.
This support article details the expected steps I'm hoping to emulate in the sandbox environment: https://ppmts.custhelp.com/app/answers/detail/a_id/622/kw/Dispute
What you'll need to do is create your own IPN simulator to test this. You can make a basic HTML form with the action set to your IPN URL and hidden fields that match the names/values you expect to get from an IPN.
This way you can load your test in a browser and submit it to your IPN listener. You'll be able to see the results on screen which can help with troubleshooting.
Keep in mind that when testing this way the data is not coming from PayPal's server so the IPN will be unverified. You'll need to make sure your code logic handles that.
Here are some samples of IPN's you'd get when a chargeback occurs so you can see what you should expect and setup your simulator accordingly.
New Case
txn_type = new_case
payment_date = 13:40:52 Aug 05, 2013 PDT
case_id = PP-002-576-509-683
receipt_id = 4674-2219-3481-3741
case_type = chargeback
business = payments#domain.com
verify_sign = AeD56uUedZzgp83xxTHMkZtMZ9FVAzvpMwl6OHUf9CNvlvgA2P0mbcwP
payer_email = 9FE47613HE5558457#dcc.paypal.com
txn_id = 0PC8014855508203X
case_creation_date = 18:40:23 Sep 04, 2013 PDT
receiver_email = payments#domain.com
payer_id = RZ3LX555U646Q
receiver_id = M5VRA555CSK6
reason_code = non_receipt
custom =
charset = windows-1252
notify_version = 3.7
ipn_track_id = 2842c24f40ac
Reversal
mc_gross = -1972.86
protection_eligibility = Ineligible
payer_id = RZ3LX555U646Q
address_street = N/A
payment_date = 18:42:00 Sep 04, 2013 PDT
payment_status = Reversed
charset = windows-1252
address_zip = 00000
first_name = Tester
mc_fee = -44.74
address_country_code = US
address_name = Tester Testerson
notify_version = 3.7
reason_code = chargeback
custom =
business = payments#usbswiper.com
address_country = United States
address_city = NA
verify_sign = Ai1PaghZh5FmBLCDCTQpwG8jB264ABWpa3tbhFljkaPnVj1L9ip5EwyS
parent_txn_id = 0PC8014555008203X
txn_id = 0PC8014855508203X
payment_type = instant
last_name = Testerson
address_state = NA
receiver_email = payments#domain.com
payment_fee = -44.74
receiver_id = M5VRA555CSK6
item_name = PayPal POS Web Order
mc_currency = USD
item_number =
residence_country = US
receipt_id = 4674-2219-3481-3741
handling_amount = 0.00
transaction_subject =
payment_gross = -1972.86
shipping = 100.00
ipn_track_id = f456d076de1ff
I need a Form authentication over 3 Sites (login.mydomain.com, www.mydomain.com and admin.mydomain.com). Users are from a MSSQL-DB, but I don't think that's a problem.
I've set up my web.config as described here: http://msdn.microsoft.com/en-us/library/eb0zx8fc.aspx , but it doesn't work.
My code for the login:
string RoleString = string.Empty;
RoleString = user.Gruppe.Bezeichnung;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, user.Username, DateTime.Now, DateTime.Now.AddMinutes(2), false, user.Gruppe.name, FormsAuthentication.FormsCookiePath);
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hash);
cookie.Name = "UserCookie";
cookie.Domain = ".mydomain.com";
Response.Cookies.Add(cookie);
Response.Redirect("http://www.mydomain.com/Default.aspx");
What could be the problem? I tried with machine key in webconfig, but that gave me an error with the Viewstate of the MAC...
I would like to send an encrypted EMail Message with Exchange WEb Services using C#.
Is there any possibillity?
Thanks
Edit:
My Mail body encrypter:
public static byte[] encry(string body, ContentTyp typ, string to )
{
X509Certificate2 cert = GetMailCertificate(to);
StringBuilder msg = new StringBuilder();
msg.AppendLine(string.Format("Content-Type: text/{0}; charset=\"iso-8859-1\"", typ.ToString()));
msg.AppendLine("Content-Transfer-Encoding: 7bit");
msg.AppendLine();
msg.AppendLine(body);
EnvelopedCms envelope = new EnvelopedCms(new ContentInfo(Encoding.UTF8.GetBytes(msg.ToString())));
CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert);
envelope.Encrypt(recipient);
//System.IO.MemoryStream ms = new System.IO.MemoryStream(envelope.Encode());
return envelope.Encode();
}
Main
byte [] con = encrypted.encry("test", encrypted.ContentTyp.plain, "test#server.com");
EmailMessage msg1 = new EmailMessage(_server);
msg1.MimeContent = new MimeContent("UTF-8", con);
msg1.ToRecipients.Add("user#server.com");
msg1.InternetMessageHeaders = ??
msg1.Send();
If you are referring to S/Mime encryption, then you'll have to create the encrypted message according to RFC 3852 and RFC 4134. After you've done that, you can send the message.
Using the EWS Managed API, this can be done as follows:
var item = new EmailMessage(service);
item.MimeContent = new MimeContent(Encoding.ASCII.HeaderName, content);
// Set recipient infos, etc.
item.Send();
EDIT:
You should add the standard headers like From, To, Date, Subject, etc. And the content-type.
Subject: Test
From: "sender" <sender#yourcompany.com>
To: "recipient" <recipient#othercompany.com>
Content-Type: application/pkcs7-mime; smime-type=signed-data; name=smime.p7m
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m
Your encrypted body goes here
Just use a StringWriter put all that together. The result is your MIME body.