Adaptive Payments giving Exception on Web Server in c# - c#

I am working on Delayed Chained Payments Module in Adaptive Payments in Paypal. I am Using AdaptivePaymentsCoreSdk for it and it is working fine on LocalHost as well as one web Server. All working is going Fine. But when I Deploy my application on another Server than On Service.Pay I am Getting an Exception. Exception is as Follows:-
PayPal.Exception.ConnectionException: Invalid HTTP response The underlying connection was closed: An unexpected error occurred on a receive.
at PayPal.HttpConnection.Execute(String payLoad, HttpWebRequest httpRequest)
at PayPal.APIService.MakeRequestUsing(IAPICallPreHandler apiCallHandler)
at PayPal.BasePayPalService.Call(IAPICallPreHandler apiCallHandler)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest, String apiUserName)
at PayPal.AdaptivePayments.AdaptivePaymentsService.Pay(PayRequest payRequest)
at Payme101.Controllers.HomeController.Order_Pay(Order_Pay single) in d:\Completed\Payme10\Payme101\Payme101\Controllers\HomeController.cs:line 2404
My Code is As Follows:-
PayRequest request = new PayRequest();
RequestEnvelope requestEnvelope = new RequestEnvelope("en_US");
ReceiverList receiverList = new ReceiverList();
request.requestEnvelope = requestEnvelope;
Receiver receiver1 = new Receiver();
receiver1.amount = 10;
receiver1.email = "Primary Email ID";
receiver1.primary = true;
receiver1.invoiceId = str;
Receiver receiver2 = new Receiver();
receiver2.amount = 8;
receiver2.email = SellerMail;
receiver2.primary = false;
receiver2.invoiceId = str;
receiverList.receiver.Add(receiver1);
receiverList.receiver.Add(receiver2);
request.receiverList = receiverList;
request.actionType = "PAY_PRIMARY";
request.currencyCode = "USD";
request.returnUrl = "http://ServerIP/Home/complete/?payKey=${payKey}";
request.cancelUrl = "http://ServerIP/Home/cancel?payKey=${payKey}";
//request.returnUrl = "http://localhost:1735/Home/complete/?payKey=${payKey}";
//request.cancelUrl = "http://localhost:1735/Home/cancel?payKey=${payKey}";
AdaptivePaymentsService service = null;
PayResponse response = null;
try
{
Dictionary<string, string> configurationMap = Configuration.GetAcctAndConfig();
service = new AdaptivePaymentsService(configurationMap);
response = service.Pay(request);
}
catch (Exception ex)
{
//Here I am getting Exception.
return RedirectToAction("Order_Pay2", "Home", new { id = ex.ToString() });
}
Dictionary<string, string> responseValues = new Dictionary<string, string>();
string redirectUrl = null;
if (!response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILURE.ToString()) && !response.responseEnvelope.ack.ToString().Trim().ToUpper().Equals(AckCode.FAILUREWITHWARNING.ToString()))
{
redirectUrl = "https://www.sandbox.paypal.com/us/cgi-bin/webscr?cmd=_ap-payment&paykey=" + response.payKey;
return Redirect(redirectUrl);
}
Can Anybody tell me what I am doing wrong and What should i change to Remove this Exception And Make Payment Successfull.
Thanks in Advance...

Related

AndroidPublisherService - Play Developer API Client - Upload aab failes due to bad credentials

Trying to make use of the AndroidPublisherService from Play Developer API Client.
I can list active tracks and the releases in those tracks, but when I try to upload a new build there seems to be no way of attaching the authentication already made previously to read data.
I've authenticated using var googleCredentials = GoogleCredential.FromStream(keyDataStream) .CreateWithUser(serviceUsername); where serviceUsername is the email for my service account.
private static void Execute(string packageName, string aabfile, string credfile, string serviceUsername)
{
var credentialsFilename = credfile;
if (string.IsNullOrWhiteSpace(credentialsFilename))
{
// Check env. var
credentialsFilename =
Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS",
EnvironmentVariableTarget.Process);
}
Console.WriteLine($"Using credentials {credfile} with package {packageName} for aab file {aabfile}");
var keyDataStream = File.OpenRead(credentialsFilename);
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername);
var credentials = googleCredentials.UnderlyingCredential as ServiceAccountCredential;
var service = new AndroidPublisherService();
var edit = service.Edits.Insert(new AppEdit { ExpiryTimeSeconds = "3600" }, packageName);
edit.Credential = credentials;
var activeEditSession = edit.Execute();
Console.WriteLine($"Edits started with id {activeEditSession.Id}");
var tracksList = service.Edits.Tracks.List(packageName, activeEditSession.Id);
tracksList.Credential = credentials;
var tracksResponse = tracksList.Execute();
foreach (var track in tracksResponse.Tracks)
{
Console.WriteLine($"Track: {track.TrackValue}");
Console.WriteLine("Releases: ");
foreach (var rel in track.Releases)
Console.WriteLine($"{rel.Name} version: {rel.VersionCodes.FirstOrDefault()} - Status: {rel.Status}");
}
using var fileStream = File.OpenRead(aabfile);
var upload = service.Edits.Bundles.Upload(packageName, activeEditSession.Id, fileStream, "application/octet-stream");
var uploadProgress = upload.Upload();
if (uploadProgress == null || uploadProgress.Exception != null)
{
Console.WriteLine($"Failed to upload. Error: {uploadProgress?.Exception}");
return;
}
Console.WriteLine($"Upload {uploadProgress.Status}");
var tracksUpdate = service.Edits.Tracks.Update(new Track
{
Releases = new List<TrackRelease>(new[]
{
new TrackRelease
{
Name = "Roswell - Grenis Dev Test",
Status = "completed",
VersionCodes = new List<long?>(new[] {(long?) upload?.ResponseBody?.VersionCode})
}
})
}, packageName, activeEditSession.Id, "internal");
tracksUpdate.Credential = credentials;
var trackResult = tracksUpdate.Execute();
Console.WriteLine($"Track {trackResult?.TrackValue}");
var commitResult = service.Edits.Commit(packageName, activeEditSession.Id);
Console.WriteLine($"{commitResult.EditId} has been committed");
}
And as the code points out, all action objects such as tracksList.Credential = credentials; can be given the credentials generated from the service account.
BUT the actual upload action var upload = service.Edits.Bundles.Upload(packageName, activeEditSession.Id, fileStream, "application/octet-stream"); does not expose a .Credential object, and it always fails with:
The service androidpublisher has thrown an exception: Google.GoogleApiException: Google.Apis.Requests.RequestError
Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project. [401]
Errors [
Message[Login Required.] Location[Authorization - header] Reason[required] Domain[global]
]
at Google.Apis.Upload.ResumableUpload`1.InitiateSessionAsync(CancellationToken cancellationToken)
at Google.Apis.Upload.ResumableUpload.UploadAsync(CancellationToken cancellationToken)
So, how would I go about providing the actual Upload action with the given credentials here?
Managed to figure this out during the day, I was missing one call to CreateScoped() when creating the GoogleCredential object as well as a call to InitiateSession() on the upload object.
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername)
.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
Once that was done I could then get a valid oauth token by calling
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername)
.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
var credentials = googleCredentials.UnderlyingCredential as ServiceAccountCredential;
var oauthToken = credentials?.GetAccessTokenForRequestAsync(AndroidPublisherService.Scope.Androidpublisher).Result;
And I can now use that oauth token in the upload request:
upload.OauthToken = oauthToken;
_ = await upload.InitiateSessionAsync();
var uploadProgress = await upload.UploadAsync();
if (uploadProgress == null || uploadProgress.Exception != null)
{
Console.WriteLine($"Failed to upload. Error: {uploadProgress?.Exception}");
return;
}
The full code example for successfully uploading a new aab file to google play store internal test track thus looks something like this:
private async Task UploadGooglePlayRelease(string fileToUpload, string changeLogFile, string serviceUsername, string packageName)
{
var serviceAccountFile = ResolveServiceAccountCertificateInfoFile();
if (!serviceAccountFile.Exists)
throw new ApplicationException($"Failed to find the service account certificate file. {serviceAccountFile.FullName}");
var keyDataStream = File.OpenRead(serviceAccountFile.FullName);
var googleCredentials = GoogleCredential.FromStream(keyDataStream)
.CreateWithUser(serviceUsername)
.CreateScoped(AndroidPublisherService.Scope.Androidpublisher);
var credentials = googleCredentials.UnderlyingCredential as ServiceAccountCredential;
var oauthToken = credentials?.GetAccessTokenForRequestAsync(AndroidPublisherService.Scope.Androidpublisher).Result;
var service = new AndroidPublisherService();
var edit = service.Edits.Insert(new AppEdit { ExpiryTimeSeconds = "3600" }, packageName);
edit.Credential = credentials;
var activeEditSession = await edit.ExecuteAsync();
_logger.LogInformation($"Edits started with id {activeEditSession.Id}");
var tracksList = service.Edits.Tracks.List(packageName, activeEditSession.Id);
tracksList.Credential = credentials;
var tracksResponse = await tracksList.ExecuteAsync();
foreach (var track in tracksResponse.Tracks)
{
_logger.LogInformation($"Track: {track.TrackValue}");
_logger.LogInformation("Releases: ");
foreach (var rel in track.Releases)
_logger.LogInformation($"{rel.Name} version: {rel.VersionCodes.FirstOrDefault()} - Status: {rel.Status}");
}
var fileStream = File.OpenRead(fileToUpload);
var upload = service.Edits.Bundles.Upload(packageName, activeEditSession.Id, fileStream, "application/octet-stream");
upload.OauthToken = oauthToken;
_ = await upload.InitiateSessionAsync();
var uploadProgress = await upload.UploadAsync();
if (uploadProgress == null || uploadProgress.Exception != null)
{
Console.WriteLine($"Failed to upload. Error: {uploadProgress?.Exception}");
return;
}
_logger.LogInformation($"Upload {uploadProgress.Status}");
var releaseNotes = await File.ReadAllTextAsync(changeLogFile);
var tracksUpdate = service.Edits.Tracks.Update(new Track
{
Releases = new List<TrackRelease>(new[]
{
new TrackRelease
{
Name = $"{upload?.ResponseBody?.VersionCode}",
Status = "completed",
InAppUpdatePriority = 5,
CountryTargeting = new CountryTargeting { IncludeRestOfWorld = true },
ReleaseNotes = new List<LocalizedText>(new []{ new LocalizedText { Language = "en-US", Text = releaseNotes } }),
VersionCodes = new List<long?>(new[] {(long?) upload?.ResponseBody?.VersionCode})
}
})
}, packageName, activeEditSession.Id, "internal");
tracksUpdate.Credential = credentials;
var trackResult = await tracksUpdate.ExecuteAsync();
_logger.LogInformation($"Track {trackResult?.TrackValue}");
var commitResult = service.Edits.Commit(packageName, activeEditSession.Id);
commitResult.Credential = credentials;
await commitResult.ExecuteAsync();
_logger.LogInformation($"{commitResult.EditId} has been committed");
}

Web request CSharp

I have a C# code that consumes a web service data from an external site. it was working and displaying the weather data on my page but now it throws "An exception occurred during a WebClient request" error. I was trying to research this but no luck.
protected void GetWeatherInfo(string url)
{
string url1 = string.Format(url);
using (WebClient client = new WebClient())
{
WebProxy proxyObj = new WebProxy(url1);
proxyObj.Credentials = CredentialCache.DefaultCredentials;
client.Proxy = proxyObj;
try
{
string json = client.DownloadString(url1);
WeatherInfo weatherInfo = (new JavaScriptSerializer()).Deserialize<WeatherInfo>(json);
lblCity_Country.Text = weatherInfo.city.name + "," + weatherInfo.city.country;
imgCountryFlag.ImageUrl = string.Format("http://openweathermap.org/images/flags/{0}.png", weatherInfo.city.country.ToLower());
lblDescription.Text = weatherInfo.list[0].weather[0].description;
imgWeatherIcon.ImageUrl = string.Format("http://openweathermap.org/img/w/{0}.png", weatherInfo.list[0].weather[0].icon);
lblTempMin.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.min, 1));
lblTempMax.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.max, 1));
lblTempDay.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.day, 1));
lblTempNight.Text = string.Format("{0}°С", Math.Round(weatherInfo.list[0].temp.night, 1));
lblHumidity.Text = weatherInfo.list[0].humidity.ToString();
tblWeather.Visible = true;
}
catch (Exception ex)
{
string excep = ex.Message;
}
}
}

Woocommerce REST API V2: The remote server returned an error: (401) Unauthorized. Status ProtocolError

I want to update order status through Woocommerce REST Api V2 in my windows service project. I got a sample C# code to download orders from this link
Consuming WooCommerce REST API from C#
Its working fine as I am downloading orders from my local server.
But I want to update order/add order note.
I tried this
public string UpdateOrder()
{
//return MakeApiCall_mine("orders/17", new Dictionary<string, string>() { { "order", "{\"status\":\"completed\"}" } });//
return MakeApiCall_mine("orders/17");
}
private string MakeApiCall_mine(string endpoint, Dictionary<string, string> parameters = null, string method = "PUT")
{
if (parameters == null)
{
parameters = new Dictionary<string, string>();
}
parameters["oauth_consumer_key"] = this.ConsumerKey;
parameters["oauth_timestamp"] =
DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds.ToString();
parameters["oauth_timestamp"] = parameters["oauth_timestamp"].Substring(0,
parameters["oauth_timestamp"].IndexOf("."));
parameters["oauth_nonce"] = Hash(parameters["oauth_timestamp"]);
parameters["oauth_signature_method"] = "HMAC-SHA256";
parameters["oauth_signature"] = GenerateSignature(parameters, method, endpoint);
WebClient wc = new WebClient();
StringBuilder sb = new StringBuilder();
foreach (var pair in parameters)
{
sb.AppendFormat("&{0}={1}", HttpUtility.UrlEncode(pair.Key), HttpUtility.UrlEncode(pair.Value));
}
var url = this.ApiUrl + endpoint + "?" + sb.ToString().Substring(1).Replace("%5b", "%5B").Replace("%5d", "%5D");
//var result = wc.DownloadString(url);
wc.UploadString(url, "{\"order\":{\"status\":\"completed\"}}");
//return result;
return "";
}
but getting error The remote server returned an error: (401) Unauthorized
My woocommerce user Permissions:Read/Write.

trying to send email request but i get exception

I am trying to create and send an email request in crm2011. I have the email, but when I try to send it I get an exception:
email With Id = 00000000-0000-0000-0000-000000000000 Does Not Exist.
Here's my code:
OrganizationServiceProxy p = new OrganizationServiceProxy(
new Uri(""), null, ccr, null);
WhoAmIRequest systemUserRequest = new WhoAmIRequest();
WhoAmIResponse systemUserResponse = (WhoAmIResponse)p.Execute(systemUserRequest);
Guid _userId = systemUserResponse.UserId;
Entity email = new Entity("email");
email.Attributes.Add("subject", "test");
Entity[] To = new Entity[1];
To[0] = new Entity("activityparty");
To[0]["partyid"] = new EntityReference("contact", new Guid("some guidid"));
email.Attributes.Add("to", To);
Entity[] From = new Entity[1];
From[0] = new Entity("activityparty");
From[0]["partyid"] = new EntityReference("systemuser", _userId);
email.Attributes.Add("from", From);
try
{
Guid emailGuid = p.Create(email);
}
catch (Exception e)
{
Console.WriteLine("error " + e.Message);
Console.ReadLine();
}
OrganizationRequest request = new OrganizationRequest() { RequestName = "SendEmail" };
request["EmailId"] = email.Id;
request["TrackingToken"] = "";
request["IssueSend"] = true;
// THE CODE FAILS HERE:
OrganizationResponse rsp = p.Execute(request);
The main error is in this line:
request["EmailId"] = email.Id;
when you create the email, the Id property is not filled inside the record but the Guid is inside the variable emailGuid
I suggest to change the code in this way :
try
{
Guid emailGuid = p.Create(email);
OrganizationRequest request = new OrganizationRequest() { RequestName = "SendEmail" };
request["EmailId"] = emailGuid; // now is the right variable
request["TrackingToken"] = "";
request["IssueSend"] = true;
OrganizationResponse rsp = p.Execute(request);
}
catch (Exception e)
{
Console.WriteLine("error " + e.Message);
Console.ReadLine();
}

'Security header is not valid' using PayPal sandbox in .NET

I am using the PayPal sandbox in ASP.Net C# 4.0. I added the following web references:
https://www.sandbox.paypal.com/wsdl/PayPalSvc.wsdl
https://www.paypalobjects.com/wsdl/PayPalSvc.wsdl
When I run this code:
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq req = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutRequestType()
{
Version = Version,
SetExpressCheckoutRequestDetails = reqDetails
}
};
// query PayPal and get token
PayPalAPIHelper.PayPalSandboxWS.SetExpressCheckoutResponseType resp = BuildPayPalSandboxWebservice().SetExpressCheckout(req);
In my resp object, the error message says:
Security header is not valid
I was told to give it correct API credentials. I signed up on developer.paypal.com and i'm assuming the email address and password i used are my valid credentials. How and where do I give it my API credentials? Thanks
Did you check the endpoint addresses in your web.config file
Those should be referenced to following url's
For API Certificate => SOAP https://api.sandbox.paypal.com/2.0/
For API Signature => SOAP https://api-3t.sandbox.paypal.com/2.0/
If you are using Signature then use the following code
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"], //Not paypal login username
Password = ConfigurationManager.AppSettings["PayPalPassword"], //not login password
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
To get Paypal signature follow the link
For more info click here
Update:
Please check the following code it is working for me
CustomSecurityHeaderType type = new CustomSecurityHeaderType();
type.Credentials = new UserIdPasswordType()
{
Username = ConfigurationManager.AppSettings["PayPalUserName"],
Password = ConfigurationManager.AppSettings["PayPalPassword"],
Signature = ConfigurationManager.AppSettings["PayPalSignature"]
};
PaymentDetailsItemType[] pdItem = new PaymentDetailsItemType[1];
pdItem[0] = new PaymentDetailsItemType()
{
Amount = new BasicAmountType(){currencyID = CurrencyCodeType.USD,Value = ItemPrice},
Name = ItemName,
Number = ItemNumber,
Description = ItemDescription,
ItemURL = ItemUrl
};
SetExpressCheckoutRequestDetailsType sdt = new SetExpressCheckoutRequestDetailsType();
sdt.NoShipping = "1";
PaymentDetailsType pdt = new PaymentDetailsType()
{
OrderDescription = OrderDesc,
PaymentDetailsItem = pdItem,
OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.USD,
Value = ItemPrice
}
};
sdt.PaymentDetails = new PaymentDetailsType[] { pdt };
sdt.CancelURL = "http://localhost:62744/PaymentGateway/PaymentFailure.aspx";
sdt.ReturnURL = "http://localhost:62744/PaymentGateway/ExpressCheckoutSuccess.aspx";
SetExpressCheckoutReq req = new SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
{
SetExpressCheckoutRequestDetails = sdt,
Version = "92.0"
}
};
var paypalAAInt = new PayPalAPIAAInterfaceClient();
var resp = paypalAAInt.SetExpressCheckout(ref type, req);
if (resp.Errors != null && resp.Errors.Length > 0)
{
// errors occured
throw new Exception("Exception(s) occured when calling PayPal. First exception: " +
resp.Errors[0].LongMessage);
}
Response.Redirect(string.Format("{0}?cmd=_express-checkout&token={1}",
ConfigurationManager.AppSettings["PayPalOriginalUrl"], resp.Token));

Categories