Paypal Invoice SDK Service Call + Express Checkout + Recurrying Payment issue - paypal-nvp

Hi I have implemented Paypal Invoice, Express Checkout & Recurring Payments services using adaptive methods (NVP) call. It is working fine on my local system with sandbox account but not on development server and facing problem wherever I have called the paypal services based on request.
Code
InvoiceModelAlias.PaymentTermsType paymentTermsType = (InvoiceModelAlias.PaymentTermsType)Enum.Parse(typeof(InvoiceModelAlias.PaymentTermsType),invoice.PaymentTerms.ToUpper());
InvoiceModelAlias.CreateAndSendInvoiceRequest invoiceRequest = new InvoiceModelAlias.CreateAndSendInvoiceRequest();
invoiceRequest.requestEnvelope = new InvoiceModelAlias.RequestEnvelope();
invoiceRequest.requestEnvelope.errorLanguage = "en_US";
invoiceRequest.invoice = new InvoiceModelAlias.InvoiceType();
invoiceRequest.invoice.currencyCode = invoice.CurrencyCode;
invoiceRequest.invoice.merchantEmail = invoice.MerchantEmail;
invoiceRequest.invoice.payerEmail = invoice.PayerEmail;
invoiceRequest.invoice.paymentTerms = paymentTermsType;
invoiceRequest.invoice.itemList = new InvoiceModelAlias.InvoiceItemListType();
invoiceRequest.invoice.itemList.item = new List<InvoiceModelAlias.InvoiceItemType>();
invoiceRequest.invoice.itemList.item.Add(new InvoiceModelAlias.InvoiceItemType(invoice.ItemName, Convert.ToDecimal(invoice.ItemQuantity), Convert.ToDecimal(invoice.ItemAmount)));
InvoiceAlias.InvoiceService invoiceService;
InvoiceModelAlias.CreateAndSendInvoiceResponse invoiceResponse = null;
invoiceService = GetService();
invoiceResponse = invoiceService.CreateAndSendInvoice(invoiceRequest);
string ackRsponse = invoiceResponse.responseEnvelope.ack.ToString();
invoiceService.CreateAndSendInvoice(invoiceRequest)
Exception
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.Invoice.InvoiceService.CreateAndSendInvoice(CreateAndSendInvoiceRequest createAndSendInvoiceRequest, String apiUserName)
at PayPal.Invoice.InvoiceService.CreateAndSendInvoice(CreateAndSendInvoiceRequest createAndSendInvoiceRequest)
at DoPayments.Payments.Invoices.CreateAndSendInvoice(Invoice invoice)
Will you please someone help me to get this out or suggest whats the reason behind this as it is working fine at local but not on development/production server.
Same kind of issue I am facing in case of express checkout and recurring payment methods too which is below:
com.paypal.sdk.exceptions.FatalException: The underlying connection was closed: An unexpected error occurred on a receive.
at com.paypal.sdk.core.nvp.NVPAPICaller.Call(String NvpRequest)
at com.paypal.sdk.services.NVPCallerServices.Call(String requestnvp)
Thanks in advance.

Related

ChatBot did not work in Web Emulator but work well in Local Bot Framework emulator

I developed the ChatBot that integrates with SharePoint On Premise. When I debug the ChatBot in emulator, it work. But When I debug on Web Emulator in Azure and Website Hosted in Company Website by using DirectLine, it did not work.
Does anyone know how to solve it?
Herewith my screenshot.
Left hand side is from Web Emulator, Right hand side is from local Bot Framework Emulator
Update with Source Code (09 December 2019)
XmlNamespaceManager xmlnspm = new XmlNamespaceManager(new NameTable());
Uri sharepointUrl = new Uri("https://mvponduty.sharepoint.com/sites/sg/daw/");
xmlnspm.AddNamespace("atom", "http://www.w3.org/2005/Atom");
xmlnspm.AddNamespace("d", "http://schemas.microsoft.com/ado/2007/08/dataservices");
xmlnspm.AddNamespace("m", "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata");
NetworkCredential cred = new System.Net.NetworkCredential("engsooncheah#mvponduty.onmicrosoft.com", "Pa$$w0rd", "mvponduty.onmicrosoft.com");
HttpWebRequest listRequest = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + "_api/lists/getByTitle('" + "data#work" + "')/items?$filter=Keywords%20eq%20%27bloomberg%27");
listRequest.Method = "GET";
listRequest.Accept = "application/atom+xml";
listRequest.ContentType = "application/atom+xml;type=entry";
listRequest.Credentials = cred;
//LINE 136 start from below
HttpWebResponse listResponse = (HttpWebResponse)listRequest.GetResponse();
StreamReader listReader = new StreamReader(listResponse.GetResponseStream());
XmlDocument listXml = new XmlDocument();
listXml.LoadXml(listReader.ReadToEnd());
if (listResponse.StatusCode == HttpStatusCode.OK)
{
Console.WriteLine("Connected");
await turnContext.SendActivityAsync("Connected");
}
// Get and display all the document titles.
XmlElement root = listXml.DocumentElement;
XmlNodeList elemList = root.GetElementsByTagName("content");
XmlNodeList elemList_title = root.GetElementsByTagName("d:Title");
XmlNodeList elemList_desc = root.GetElementsByTagName("d:Description");
//for LINK
XmlNodeList elemList_Id = root.GetElementsByTagName("d:Id");
XmlNodeList elemList_Source = root.GetElementsByTagName("d:Sources");
XmlNodeList elemList_ContentTypeId = root.GetElementsByTagName("d:ContentTypeId");
var attachments = new List<Attachment>();
for (int i = 0; i < elemList.Count; i++)
{
string title = elemList_title[i].InnerText;
string desc = elemList_desc[i].InnerText;
string baseurllink = "https://mvponduty.sharepoint.com/sites/sg/daw/Lists/data/DispForm.aspx?ID=";
string LINK = baseurllink + elemList_Id[i].InnerText + "&Source=" + elemList_Source[i].InnerText + "&ContentTypeId=" + elemList_ContentTypeId[i].InnerText;
//// Hero Card
var heroCard = new HeroCard(
title: title.ToString(),
text: desc.ToString(),
buttons: new CardAction[]
{
new CardAction(ActionTypes.OpenUrl,"LINK",value:LINK)
}
).ToAttachment();
attachments.Add(heroCard);
}
var reply = MessageFactory.Carousel(attachments);
await turnContext.SendActivityAsync(reply);
Update 17 December 2019
I had try using Embedded and Direct Line. But the Error still same.
The Bot is not hosted in SharePoint.
Update 06 January 2020
Its did not work in Azure Bot Services
Based on your description, you can fetch data from it locally. This means your code and logic are all right.
I noticed that your sharePoint URL is : https://mvponduty.sharepoint.com/sites/sg/daw/ and I tried to access it, and also tried to access your whole request URL : https://mvponduty.sharepoint.com/sites/sg/daw/_api/lists/getByTitle('data#work')/items?$filter=Keywords eq 'bloomberg' the response of the two are all 404.
And you said this is an on-prem site , so could you pls have a check that if this site can be reached from a public network?
I assume when you test your code locally, you can access this site as you are in your internal network which will be able to access the on-prem site. However, when you publish your code to Azure, it is not in your internal work anymore: it is in public network so that can't access your on-prem sharePoint site which caused this error.
As we know, bot code is hosted on Azure app service, if this error is caused by the above reason, maybe Azure App Service Hybrid Connections feature will be helpful in this scenario.
ChatBot seems to be working fine? it's sending and receiving messages. There's some code you have that is behaving differently when run locally versus hosted. There's Xml, is it a file or generated? You need check that it's following the same logic and using same data as when it is run locally. Maybe if you paste some of the (non confidential) code where it crashes, we can have more ideas how to help
When you publish your bot, there will be an option as below :
Select Edit App Service Settings. Add only the following details, nothing else :
MicrosoftAppId : <xxxxx>
MicrosoftAppPassword : <xxxxx>
Click Apply, Ok.
Make sure you remove the Microsoft App Id and Microsoft App Password from appsettings.json, so that it works in bot emulator as well.
Now Publish the bot. It will work at both places.
Hope this is helpful.

When creating an IServiceManagement for Dynamics 365, why does the authentication endpoint respond with an HTML sign in page?

I have some integration code that intends to use the Organization Service via the CRM SDK.
On one environment, creating an IServiceManagement<IOrganizationService>:
IServiceManagement<IOrganizationService> orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri("dynamics uri")));
and then authenticating with service account credentials:
AuthenticationCredentials authCredentials = new AuthenticationCredentials();
authCredentials.ClientCredentials.UserName.UserName = _config.GetValue<string>("Dynamics:Username");
authCredentials.ClientCredentials.UserName.Password = _config.GetValue<string>("Dynamics:Password");
AuthenticationCredentials tokenCredentials = orgServiceManagement.Authenticate(authCredentials);
works fine.
On another Dynamics environment, the call to GetServiceManagement fails with the following error message:
System.InvalidOperationException
HResult=0x80131509
Message=Metadata contains a reference that cannot be resolved: 'https://login.microsoftonline.com/[guid]/oauth2/authorize?client_id=[some client id]&response_mode=form_post&response_type=code+id_token&scope=openid+profile&state=OpenIdConnect.AuthenticationProperties%[some base-64]RedirectTo%3dhttps%253a%252f%252ftst-success.crm4.dynamics.com%252f&nonce=[some nonce]&redirect_uri=https:%2f%2fcloudredirector.crm4.dynamics.com%2fG%2fAuthRedirect%2fIndex.aspx&max_age=86400'.
Source=System.ServiceModel
StackTrace:
at System.ServiceModel.Description.MetadataExchangeClient.MetadataRetriever.Retrieve(TimeoutHelper timeoutHelper)
at System.ServiceModel.Description.MetadataExchangeClient.ResolveNext(ResolveCallState resolveCallState)
at System.ServiceModel.Description.MetadataExchangeClient.GetMetadata(MetadataRetriever retriever)
at System.ServiceModel.Description.MetadataExchangeClient.GetMetadata(Uri address, MetadataExchangeClientMode mode)
at Microsoft.Xrm.Sdk.Client.ServiceMetadataUtility.RetrieveServiceEndpointMetadata(Type contractType, Uri serviceUri, Boolean checkForSecondary)
at Microsoft.Xrm.Sdk.Client.ServiceConfiguration`1..ctor(Uri serviceUri, Boolean checkForSecondary)
at Microsoft.Xrm.Sdk.Client.ServiceConfigurationFactory.CreateConfiguration[TService](Uri serviceUri, Boolean enableProxyTypes, Assembly assembly)
at Microsoft.Xrm.Sdk.Client.ServiceConfigurationFactory.CreateConfiguration[TService](Uri serviceUri)
at CrmAuthTest.Program.Main(String[] args) in c:\users\t.wolverson\Source\Repos\CrmAuthTest\CrmAuthTest\Program.cs:line 18
Inner Exception 1:
XmlException: CData elements not valid at top level of an XML document. Line 1, position 3.
(I have masked the bits which look identifying or cryptographic)
POSTing to this URL in PostMan yields the HTML for a browser login page, which explains the failure; this isn't what the ServiceConfigurationFactory expects. The scenario is not user-interactive, so this would never make sense, there is no browser and no user able to interact with it.
What do I have to change in Dynamics CRM Online to stop it doing this, and make it just work normally?
Do you instantiate your OrganizationServiceProxy depending on the AuthenticationProviderType right after the lines of code you have posted? Like this
var orgServiceManagement = ServiceConfigurationFactory.CreateManagement<IOrganizationService>(new Uri(ConfigurationManager.AppSettings["CrmUrlService"]));
var authCredentials = new AuthenticationCredentials();
authCredentials.ClientCredentials.UserName.UserName = ConfigurationManager.AppSettings["CrmUserName"];
authCredentials.ClientCredentials.UserName.Password = ConfigurationManager.AppSettings["CrmPassword"];
var tokenCredentials = orgServiceManagement.Authenticate(authCredentials);
IOrganizationService _service;
switch (orgServiceManagement.AuthenticationType)
{
case AuthenticationProviderType.ActiveDirectory:
_service = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.ClientCredentials);
break;
default:
_service = new OrganizationServiceProxy(orgServiceManagement, tokenCredentials.SecurityTokenResponse);
break;
}
Even if this solves your problem, I recommend that you use CrmServiceClient instead. This class can be found in Microsoft.Xrm.Tooling.Connector dll. It is the go to authentication class when building Windows client applications that connect to Microsoft Dynamics 365. More information on this can be found here
Here is an example on how to initialize CrmServiceClient when connecting to Dynamics 365 online using Office 365:
var myConnectionString = "Url=https://[YourOrganization].crm4.dynamics.com;Username=[YourUser];Password=[YourPassword];AuthType=Office365;";
var crmClient = new CrmServiceClient(myConnectionString);
//Do your stuff
var response = crmClient.Execute(new WhoAmIRequest());
If you need other authentication methods in Dynamics Online check how to build your connection string here.
For on-premises check how to build your connection string here.

EWS Managed API 2, setting FlagStatus

I'm attempting to set the Flag on an e-mail using EWS Managed API 2 - however, I keep getting an error that I can't seem to get past.
I'm doing the following:
ExchangeService exchangeService = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
exchangeService.Url = new Uri(<ews url comes from Outlook JavaScript API>);
exchangeService.UseDefaultCredentials = false;
exchangeService.Credentials = new OAuthCredentials(<ews token comes from Outlook JavaScript API>);
And then a little later:
Item item = Item.Bind(exchangeService, new ItemId(<mail id comes from Outlook JavaScript API>), new PropertySet(ItemSchema.Flag));
item.Load();
item.Flag = new Flag() { FlagStatus = ItemFlagStatus.Flagged };
item.Update(ConflictResolutionMode.AutoResolve);
What am I missing?
I keep getting this error:
You must load or assign this property before you can read its value.
UPDATE: Ok, it turned out the this error was caused by some other code which has been corrected.
Now I'm getting this error instead:
The requested web method is unavailable to this caller or application.

Having issue in conversation of UCMA with MS Bot Framework

I am working on MS Bot Framework Integration with UCMA(Skype For Business OnPremise aka SFB onPrimise) SDK.
I am using directline channel for connection and the Connection is successfully established between two, but when a dialog prompt with Yes, No options is returned From BOT to SFB, and when I send my answer as yes then BOT do not recognize it as my answer. It creates new conversation Id for every single statement. How to overcome this issue?
Below is my code from UCMA
static DirectLineClient client = null;
client = new Microsoft.Bot.Connector.DirectLine.DirectLineClient("DirectLineSecretKey");
botConversation = client.Conversations.NewConversation();
string message = e.TextBody;
Microsoft.Bot.Connector.DirectLine.Models.Message msg = new Microsoft.Bot.Connector.DirectLine.Models.Message
{
FromProperty = "AMOL",
Text = message
};
await client.Conversations.PostMessageAsync(botConversation.ConversationId, msg);
var messages = await client.Conversations.GetMessagesAsync(botConversation.ConversationId, watermark);
InstantMessagingFlow instantMessagingFlow = (InstantMessagingFlow)sender;
watermark = messages.Watermark;
foreach (var m in messages.Messages)
{
if (m.FromProperty != "AMOL")
instantMessagingFlow.BeginSendInstantMessage(m.Text, MyMethod, instantMessagingFlow);
}
I am doing the same and it works for me. The problem in your code is, you create conversation id for each and every request and bot is considering the request as new fresh new request.
Let me know if you need any help on this.

Get "API key is missing" error when querying account details to Mailchimp API 3.0 using RestSharp

When using RestSharp to query account details in your MailChimp account I get a "401: unauthorized" with "API key is missing", even though it clearly isn't!
We're using the same method to create our RestClient with several different methods, and in all requests it is working flawlessly. However, when we're trying to request the account details, meaning the RestRequest URI is empty, we get this weird error and message.
Examples:
private static RestClient CreateApi3Client(string apikey)
{
var client = new RestClient("https://us2.api.mailchimp.com/3.0");
client.Authenticator = new HttpBasicAuthenticator(null, apiKey);
return client;
}
public void TestCases() {
var client = CreateApi3Client(_account.MailChimpApiKey);
var req1 = new RestRequest($"lists/{_account.MailChimpList}/webhooks", Method.GET);
var res1 = client.Execute(req1); // works perfectly
var req2 = new RestRequest($"automations/{account.MailChimpTriggerEmail}/emails", Method.GET);
var res2 = client.Execute(req2); // no problem
var req3 = new RestRequest(Method.GET);
var res3 = client.Execute(req3); // will give 401, api key missing
var req4 = new RestRequest(string.Empty, Method.GET);
var res4 = client.Execute(req4); // same here, 401
}
When trying the api call in Postman all is well. https://us2.api.mailchimp.com/3.0, GET with basic auth gives me all the account information and when debugging in c# all looks identical.
I'm trying to decide whether to point blame to a bug in either RestSharp or MailChimp API. Has anyone had a similar problem?
After several hours we finally found what was causing this..
When RestSharp is making the request to https://us2.api.mailchimp.com/3.0/ it's opting to omit the trailing '/'
(even if you specifically add this in the RestRequest, like: new RestRequest("/", Method.GET))
so the request was made to https://us2.api.mailchimp.com/3.0
This caused a serverside redirect to 'https://us2.api.mailchimp.com/3.0/' (with the trailing '/') and for some reason this redirect scrubbed away the authentication header.
So we tried making a
new RestRequest("/", Method.GET)
with some parameters (req.AddParameter("fields", "email")) to make it not scrub the trailing '/', but this to was failing.
The only way we were able to "fool" RestSharp was to write it a bit less sexy like:
new RestRequest("/?fields=email", Method.GET)

Resources