PayPal integration - Error #2096 in Flex Mobile - apache-flex

So i am trying to integrate PayPal in my Flex Mobile app. I make my first call like this:
(keys are sandbox by paypal dev resources)
protected function getPaypal():void {
var client_id:String="EOJ2S-Z6OoN_le_KS1d75wsZ6y0SFdVsY9183IvxFyZp";
var secret:String="EClusMEUk8e9ihI7ZdVLF5cZ6y0SFdVsY9183IvxFyZp";
var params:Object = new Object();
params.grant_type="client_credentials";
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(client_id + ":" + secret);
//var s:String = JSON.stringify(params);
paypal.contentType = "application/x-www-form-urlencoded";
paypal.headers["Authorization"] = "Basic " + encoder.toString();
paypal.method = "POST";
paypal.url = "https://api.sandbox.paypal.com/v1/oauth2/token";
paypal.send(params);
}
This fails and returns the following:
'Error #2096: The HTTP request header Basic RU9KMlMtWjZPb05fbGVfS1MxZDc1d3NaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA6RUNsdXNNRVVrOGU5
aWhJN1pkVkxGNWNaNnkwU0ZkVnNZOTE4M0l2eEZ5WnA= cannot be set via ActionScript.' faultDetail:'null'
I can't figure out what seems to be the problem.
Any help?

Maybe this?
https://stackoverflow.com/a/539173/3384609
Gist:
You can fix this by setting (in the above example)
encoder.insertNewLines = false; The default setting is true.

Related

Asp.net core disable change string in Uri

I have a Encoded string like this:
https://xx.yyy.ir/xx/ff/addUser?name=%d8%b3%d9%84%d8%a7%d9%85
But when I use Uri to convert it to a URL and send it
result = "https://xx.yyy.ir/xx/ff/addUser?name=%d8%b3%d9%84%d8%a7%d9%85"
var client = new HttpClient
{
BaseAddress = new Uri(result.ToString()),
};
var response = await client.GetAsync("");
it send this request :
https://xx.yyy.ir/xx/ff/addUser?name=سلام
why this happen? how to prevent from this?
This is what's causing your problem: new Uri(result.ToString())
Let's try to do this in a proper manner and see what happens.
var builder = new UriBuilder("https://xx.yyy.ir/xx/ff/addUser") { Port = -1 };
var query = HttpUtility.ParseQueryString(builder.Query);
query["name"] = "سلام";
builder.Query = query.ToString();
using var httpClient = new HttpClient();
var response = await client.GetAsync(builder.ToString());
builder.ToString() returns https://xx.yyy.ir/xx/ff/addUser?name=%d8%b3%d9%84%d8%a7%d9%85
So basically, the above code boils down to this:
using var httpClient = new HttpClient();
var response = await client.GetAsync("https://xx.yyy.ir/xx/ff/addUser?name=%d8%b3%d9%84%d8%a7%d9%85");
Tested and verified on my computer.

Getting error when a method is made for post request

When made I post request is made its giving internal server. Is the implementation of Flurl is fine or I am doing something wrong.
try
{
Models.PaymentPost paymentPost = new Models.PaymentPost();
paymentPost.Parts = new Models.Parts();
paymentPost.Parts.Specification = new Models.Specification();
paymentPost.Parts.Specification.CharacteristicsValue = new List<Models.CharacteristicsValue>();
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "Amount", Value = amount });
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue { CharacteristicName = "AccountReference", Value = accountId });
foreach (var item in extraParameters)
{
paymentPost.Parts.Specification.CharacteristicsValue.Add(new Models.CharacteristicsValue {
CharacteristicName = item.Key, Value = item.Value });
}
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
var selfCareUrl = "http://svdt5kubmas01.safari/auth/processPaymentAPI/v1/processPayment";
var fUrl = new Flurl.Url(selfCareUrl);
fUrl.WithBasicAuth("***", "********");
fUrl.WithHeader("X-Source-System", "POS");
fUrl.WithHeader("X-Route-ID", "STKPush");
fUrl.WithHeader("Content-Type", "application/json");
fUrl.WithHeader("X-Correlation-ConversationID", "87646eaa-2605-405e-967c-56e8002b5");
fUrl.WithHeader("X-Route-Timestamp", "150935");
fUrl.WithHeader("X-Source-Operator", " ");
var response = await clientFactory.Get(fUrl).Request().PostJsonAsync(paymentInJson).ReceiveJson<IEnumerable<IF.Models.PaymentPost>>();
return response;
}
catch (FlurlHttpException ex)
{
dynamic d = ex.GetResponseJsonAsync();
//string s = ex.GetResponseStringAsync();
return d;
}
You don't need to do this:
var paymentInJson = JsonConvert.SerializeObject(paymentPost);
PostJsonAsync just takes a regular object and serializes it to JSON for you. Here you're effectively double-serializing it and the server is probably confused by that format.
You're also doing a lot of other things that Flurl can do for you, such as creating those Url and client objects explicitly. Although that's not causing errors, this is how Flurl is typically used:
var response = await selfCareUrl
.WithBasicAuth(...)
.WithHeader(...)
...
.PostJsonAsync(paymentPost)
.ReceiveJson<List<IF.Models.PaymentPost>>();

X509Certificate2 - the system cannot find the path specified

I wish to get the data of Google analytics via service account.
When I launch first time the application, everything works correctly and I have access to the data. But When I launch second time the application I have the following error which appears: " the system cannot find the path specified ". Have you an idea? I thought it can be a lock.
This is my source code:
public static String GetAccessToken(string clientIdEMail, string keyFilePath, String scope)
{
// certificate
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
// header
var header = new { typ = "JWT", alg = "RS256" };
// claimset
var times = GetExpiryAndIssueDate();
var claimset = new
{
iss = clientIdEMail,
scope = scope,
aud = "https://accounts.google.com/o/oauth2/token",
iat = times[0],
exp = times[1],
};
JavaScriptSerializer ser = new JavaScriptSerializer();
// encoded header
var headerSerialized = ser.Serialize(header);
var headerBytes = Encoding.UTF8.GetBytes(headerSerialized);
var headerEncoded = Convert.ToBase64String(headerBytes);
// encoded claimset
var claimsetSerialized = ser.Serialize(claimset);
var claimsetBytes = Encoding.UTF8.GetBytes(claimsetSerialized);
var claimsetEncoded = Convert.ToBase64String(claimsetBytes);
// input
var input = headerEncoded + "." + claimsetEncoded;
var inputBytes = Encoding.UTF8.GetBytes(input);
// signiture
var rsa = certificate.PrivateKey as RSACryptoServiceProvider;
var cspParam = new CspParameters
{
KeyContainerName = rsa.CspKeyContainerInfo.KeyContainerName,
KeyNumber = rsa.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2,
Flags = CspProviderFlags.UseMachineKeyStore
};
var aescsp = new RSACryptoServiceProvider(1024,cspParam) { PersistKeyInCsp = false };
var signatureBytes = aescsp.SignData(inputBytes, "SHA256");
var signatureEncoded = Convert.ToBase64String(signatureBytes);
// jwt
var jwt = headerEncoded + "." + claimsetEncoded + "." + signatureEncoded;
var client = new WebClient();
client.Encoding = Encoding.UTF8;
var uri = "https://accounts.google.com/o/oauth2/token";
var content = new NameValueCollection();
content["assertion"] = jwt;
content["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer";
string response = Encoding.UTF8.GetString(client.UploadValues(uri, "POST", content));
JsonGoogleResponse result = (ser.Deserialize<JsonGoogleResponse>(response));
return result.access_token;
}
And this is the stack:
à System.Security.Cryptography.CryptographicException.ThrowCryptogaphicException(Int32 hr)
à System.Security.Cryptography.SafeProvHandle._FreeCSP(IntPtr pProvCtx)
à System.Security.Cryptography.SafeProvHandle.ReleaseHandle()
à System.Runtime.InteropServices.SafeHandle.InternalFinalize()
à System.Runtime.InteropServices.SafeHandle.Dispose(Boolean disposing)
à System.Runtime.InteropServices.SafeHandle.Finalize()
If you are running in IIS, you need to set "Load User Profile" to True in the application pool's advanced settings to be able to load a cert by filename & password.
So, I just had the exact same problem. I tried to solve it for almost 4 hours.
Problem was in passed path to key. Because I used the code from Google sample console application, where the path was just "key.p12" and the key was in the same directory as the exe file.
And when I wanted to create MVC application, I did not realize, that root of virtual server path can not be called just like "key.p12".
SOLUTION
Double check the path to the key. If it is MVC application (or another ASP web), then add the key file to the root and in code call the key by using Server.MapPath("key.p12").
I just had the same issue, in my case it was a space in the path. I have no idea why, but when I put the p12 file on c:\ root, it's working...

Facebook Credits callback in a mobile web application

I'm trying to create a Facebook Mobile Application using asp.net and MVC3 and integrate Facebook Credits as a payment method. First of all, taking the recent annoucements into consideration, is it now possible to have a mobile web application that accepts Facebook Credits?
If so, I've taken the example provided in the following post
http://www.m-webs.com/blog_facebookcredits.html
And implemented the following Controller action:
public JsonResult CallBack()
{
string fborder_info = Request.Form["order_info"];
string fborder_id = Request.Form["order_id"];
string fbmethod = Request.Form["method"];
if (fbmethod == "payments_get_items")
{
fborder_info = fborder_info.Substring(1, (fborder_info.Length - 2)); // remove the quotes
ulong credscost = 2; // Price of purchase in facebook credits
var theItem = new FacebookBuyItem()
{
item_id = 123456789,
description = "Own yours today!",
price = credscost,
title = "Digital Unicorn",
product_url = "http://www.facebook.com/images/gifts/21.png",
image_url = "http://www.facebook.com/images/gifts/21.png"
};
var res = new Dictionary<string, object>();
res["method"] = fbmethod;
res["order_id"] = fborder_id;
res["content"] = new object[] { theItem };
var jss = new JavaScriptSerializer();
var ob = jss.Serialize(res);
ob = ob.Replace("#$", #"\/".Replace("//", #"\/"));
return Json(ob, JsonRequestBehavior.AllowGet);
}
return null;
}
I've verified that the callback is being requested by facebook, and I've also captured the response being sent back, which appears to contain all of the required information to display the purchase dialog, but I'm still getting the following error message:
API Error Code: 1151
API Error Description: Sorry, but this app may not be eligible to accept Facebook Credits. If this app has accepted credits before, please try again.
Error Message: Invalid Application
and when tested from a mobile browser:
Sorry, but we're having trouble processing your payment. You have not been charged for this transaction. Please try again.
I've also noticed that my callback is being requested twice which doesn't seem right either.
Any insight into how to get my integration up and running would be greatly appreciated. My Facebook AppId is 177876855621874
Thanks.
Update: So I played around with the examples given and reverted back to webforms in order to test the example given at http://www.m-webs.com/blog_facebookcredits.html. In order to get this solution working in an asp.net MVC3 application I had to change the action type to HttpResponse instead of JsonResult which makes sense as the JsonResult leaves elements out that would normally be included in a HttpResponse.
So the Controller Action ended up looking like this:
[HttpPost]
public HttpResponse CallBack()
{
if (Request.Form["signed_request"] != null)
{
var decodeFbSignedRequest = FacebookSignedRequest.Parse(FacebookApplication.Current.AppSecret,
Request.Form["signed_request"]);
LogHelper.MicroLogMsg("SIGNED REQUEST DECODE:: " + decodeFbSignedRequest.Data);
}
string fborder_id = Request.Form["order_id"];
string fbmethod = Request.Form["method"];
string fborder_info = Request.Form["order_info"]; // Use this to look up a product on the database..
if (fbmethod == "payments_get_items")
{
int credscost = 2; // Price of purchase in facebook credits
var theItem = new FacebookBuyItem()
{
item_id = "123456AA",
description = "[Test Mode] Own yours today!",
price = credscost,
title = "[Test Mode] Digital Unicorn",
product_url = #"http:\/\/www.facebook.com\/images\/gifts\/21.png",
image_url = #"http:\/\/www.facebook.com\/images\/gifts\/21.png"
};
// Return the initial response to FB
//------------------------------------------
var res = new Dictionary<string, object>();
res["method"] = fbmethod;
res["content"] = new object[] { theItem };
var jss = new JavaScriptSerializer();
string ob = jss.Serialize(res);
LogHelper.MicroLogMsg(ob);
Response.ContentType = "application/json";
Response.Write(ob);
Response.End();
}
return null;
}
I hope this helps out anyone doing an MVC3 implementation for Facebook Credits.

language option in reCAPTCHA ASP.NET plugin

I'm using ASP.NET plugin for reCAPTCHA in my ASP.NET MVC application. Recaptcha assembly version is 1.0.4.0. Is there a way to set language to be used for RecaptchaControl?
var captchaControl = new Recaptcha.RecaptchaControl
{
ID = "recaptcha",
Theme = "blackglass",
PublicKey = "public_key",
PrivateKey = "private_key"
};
This feature was not supported in v1.0.4.0. Please download the latest version and try again.
http://code.google.com/p/recaptcha/downloads/detail?name=recaptcha-dotnet-1.0.5.0-binary.zip
with the help of this article here is how I've done it. the key is editing the generated html at the end; replacing "RecaptchaOptions = {" with "RecaptchaOptions = { lang : 'supported_language_code',"
public static string GenerateCaptcha(this HtmlHelper helper)
{
var captchaControl = new Recaptcha.RecaptchaControl
{
ID = "recaptcha",
Theme = "clean",
PublicKey = "public_key_here",
PrivateKey = "private_key_here"
};
var htmlWriter = new HtmlTextWriter(new StringWriter());
captchaControl.RenderControl(htmlWriter);
var html = htmlWriter.InnerWriter.ToString();
html = html.Replace("RecaptchaOptions = {", "RecaptchaOptions = { lang : 'tr', ");
return html;
}
EDIT: A cleaner solution is given here. (System.Web.Helpers)

Resources