I am trying to use WDSL SOAP in PHP. The initial connection seems to work fine but I am struggling to 'convert' some C# to PHP, in particular headers.
AreaSearchRequest request = new AreaSearchRequest();
request.GUID = "1234";
request.Location = "UK";
// Create AreaSearchHeader, assign AreaSearchRequest
AreaSearchHeader header = new AreaSearchHeader();
header.Request = request;
header.Validate = false;
// SOAP connection
soap.Open();
// Call the AreaSearch method response object
AreaSearchResponse response = soap.AreaSearch(header);
//Close API connection
soap.Close();
And here is my rough translation into PHP.
$wsdl = "https://whatever/";
$options = array(
'trace' => 1,
);
$client = new SoapClient($wsdl, $options);
$request = array(
'GUID' => '1234',
'Location' => 'UK',
);
$client->__soapCall('AreaSearch', $request);
What is really throwing me off is the header stuff to make a valid request! Thanks (sorry, I have no experience of C# whatsoever).
try using nusoap https://sourceforge.net/projects/nusoap/ to do the heavy lifting. I dont use PHP myself but a have a load of c# soap services that people I work with use nusoap to consume and they haven't had any issues
Related
I am new to Amazon Web Services.
I configured domain to use ElasticSearch in AWS(Amazon Web Services) console. Confirured usage of Http Requests.
Went through documantation of creating ElasticSearch client from
https://www.elastic.co/guide/en/elasticsearch/client/net-api/1.x/security.html
var response = client.RootNodeInfo(c => c
.RequestConfiguration(rc => rc
.BasicAuthentication("UserName", "Password")
));
Works fine to me (Response is 200)
But when i try to configure authentication credentials like this and pass config to client constructor i need to have "cloudId" i didnt find in at AWS where sould i search for it? or what i have to do?
My client code:
BasicAuthenticationCredentials credentials = new BasicAuthenticationCredentials("UserName", "Password");
var config = new ConnectionSettings("cloudId???", credentials);
var client = new ElasticClient(config);
var response = client.Ping();
I recently did this but a different way. I used the Nuget package AwsSignatureVersion4 and an IAM user with appropriate permissions to the ElasticSearch service.
But basically, use the ImmutableCredentials and just do what I need to do via the REST calls and the C# HttpClient. I find it easier than using the .NET ElasticSearch library. I can then copy/paste back and forth from Kibana.
var credentials = new ImmutableCredentials("access_key", "secret_key", null);
HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(someObjOrQuery), Encoding.UTF8);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var resp = httpClient.PostAsync(es_url,
httpContent,
regionName: "us-east-1",
serviceName: "es",
credentials: credentials).GetAwaiter().GetResult();
if(resp.IsSuccessStatusCode)
{
//Good to go
}
else
{
//this gets what ES sent back
var content = response.Content.ReadAsStringAsync();
dynamic respJson = JObject.Parse(content.Result());
//Now you can access stuff by dot and it's dynamic respJson.something
}
I'm trying to develop a simple application that will enable users to purchase services off a website through the Paypal API. This application is running on ASP.NET with C#.
I have had very little luck trying to get the Paypal API to co-operate. The method I'm calling is SetExpressCheckout with all the appropriate variables.
I did my research and discovered that since I'm testing in Localhost, it may affect Paypal's ability to communicate with the application. So the next thing I tried was accessing my application through an open port and a publicly accessible IP address, but the same error occurs on the call to SetExpressCheckout.
Here is the error:
Exception Details: System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
Source Error:
Line 1790: [return: System.Xml.Serialization.XmlElementAttribute("SetExpressCheckoutResponse", Namespace="urn:ebay:api:PayPalAPI")]
Line 1791: public SetExpressCheckoutResponseType SetExpressCheckout([System.Xml.Serialization.XmlElementAttribute(Namespace="urn:ebay:api:PayPalAPI")] SetExpressCheckoutReq SetExpressCheckoutReq) {
Line 1792: object[] results = this.Invoke("SetExpressCheckout", new object[] {
Line 1793: SetExpressCheckoutReq});
Line 1794: return ((SetExpressCheckoutResponseType)(results[0]));
Source File: c:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\anan_p2\730602d6\31a8d74e\App_WebReferences.c8vgyrf8.2.cs Line: 1792
I've also tried generating certificates using OpenSSL and uploading them to the Paypal account's encrypted seller option but still no effect.
Thank you very much for reading through my question!
Update: As requested here is the code being used.
String hostingOn = ConfigurationManager.AppSettings["default_site_url"];
reqDetails.ReturnURL = hostingOn + "marketplace_confirm.aspx";
reqDetails.CancelURL = hostingOn + "marketplace.aspx";
reqDetails.NoShipping = "1";
reqDetails.ReqConfirmShipping = "0";
reqDetails.OrderTotal = new BasicAmountType()
{
currencyID = CurrencyCodeType.CAD,
Value = payment_amt.Value,
};
SetExpressCheckoutReq req = new SetExpressCheckoutReq()
{
SetExpressCheckoutRequest = new SetExpressCheckoutRequestType()
{
Version = UtilPayPalAPI.Version,
SetExpressCheckoutRequestDetails = reqDetails
}
};
PayPalAPIAASoapBinding paypal = new PayPalAPIAASoapBinding();
paypal.SetExpressCheckout(req);
I am also using the https://api-aa-3t.paypal.com/2.0/ url for accessing the API
Since early 2016, Paypal started requiring TLS 1.2 protocol for communications in the Sandbox, and will enforce it for the live environment starting June 17. See here for reference.
In most .NET applications TLS 1.2 will come disabled by default, and therefore you'll need to enable it.
You need to add the following line, for example, at the beginning of you Application_Start method:
public class Site : HttpApplication
{
protected void Application_Start()
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// other configuration
}
}
You're probably connecting to api.paypal.com or api.sandbox.paypal.com, and not sending along your API certificate. The API certificate is a client SSL certificate used to complete the SSL chain.
If you don't have or are not using an API certificate, you should connect to api-3t.paypal.com or api-3t.sandbox.paypal.com for Live or Sandbox respectively.
I've been working with a PayPal (NVP/Signature) Express Checkout integration and have been hit with this SSL/TLS error.
Nothing I did seemed to get around it but then I found the following code to add above my request. For reference, I'm using MVC3/.NET 4 so Tls1.2 isn't available to me by default (like in .NET 4.5 +). This first three lines of this code gets around that. I hope it helps people!
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
ServicePointManager.DefaultConnectionLimit = 9999;
var url = "https://[paypal-api-url]/nvp";
var uri = new Uri(url);
var request = WebRequest.Create(uri);
var encoding = new UTF8Encoding();
var requestData = encoding.GetBytes(data);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.Timeout = (300 * 1000);
request.ContentLength = requestData.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(requestData, 0, requestData.Length);
}
var response = request.GetResponse();
...
Thanks a lot that really helps me.
For reference here is my code for establishing the interface in VB.NET
'Create a service Binding in code
Dim ppEndpointAddress As New System.ServiceModel.EndpointAddress("https://api-3t.sandbox.paypal.com/2.0/")
Dim ppBinding As New System.ServiceModel.BasicHttpBinding(System.ServiceModel.BasicHttpSecurityMode.Transport)
Dim ppIface As New PayPalAPI.PayPalAPIAAInterfaceClient(ppBinding, ppEndpointAddress)
Dim ppPaymentReq As New PayPalAPI.DoDirectPaymentReq()
ppPaymentReq.DoDirectPaymentRequest = ppRequest
Our internal Redmine server only allows me to connect via HTTPS. Here's how I tried to use the REST API via HTTPS from .NET:
As suggested in Using the REST API with .NET, setting the host variable to "https://redmine.company.com/redmine/" and the apiKey to "ffffffffffffffffffffffffffffffffffffffff".
From scratch with the following code:
using System.IO;
using System.Net;
class Program
{
static void Main(string[] args)
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => true;
var request = (HttpWebRequest)WebRequest.Create(
"https://redmine.company.com/redmine/issues/149.xml?key=ffffffffffffffffffffffffffffffffffffffff");
request.CookieContainer = new CookieContainer();
request.Method = "GET";
using (var response = request.GetResponse()) // Hangs here
using (var responseStream = response.GetResponseStream())
using (var memoryStream = new MemoryStream())
{
responseStream.CopyTo(memoryStream);
}
}
}
Of course, company.com and ffffffffffffffffffffffffffffffffffffffff are just placeholders for my real company and my real API key on my account page. Both attempts hang for some time before timing out with a WebException (see the Hangs here comment in attempt 2). I then tried to download other stuff from the Redmine server (like e.g. time_entries.csv, atom feeds, etc.), each time with exactly the same result.
So far so bad. However, if I copy-paste the URL https://redmine.company.com/redmine/issues/149.xml?key=ffffffffffffffffffffffffffffffffffffffff into my browser, I get exactly the response I would expect. So, it seems as though our Redmine server behaves as it should, but somehow I can't get it to work from .NET.
I have successfully downloaded stuff from other HTTPS sites and have managed to download issue data from http://demo.redmine.org with the code of attempt 2 (of course with adapted URLs, etc.). So, it seems there might be something special about how Redmine communicates over HTTPS.
If anybody is successfully using the Redmine REST API over HTTPS from .NET, I'd be really grateful for some pointers on what I'm doing wrong.
Also, suggestions on how to debug this from the client side would be greatly appreciated. So far I've tried Fiddler2, with no success. As soon as I enable its "Decrypt HTTPS traffic" setting then I no longer get an answer when I make the request in Internet Explorer.
We use redmine-net-api which supports HTTP/S connection and authentication based on API keys.
RedmineManager rm = new RedmineManager("https://<your-address>", <api-key>, "random-password");
IList<Issue> issues = rm.GetObjectList<Issue>(new NameValueCollection() { { "project_id", <project-id> } });
Try this, it works for me:
// Allow every secure connection
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, error) => true;
// Create redmine manager (where URL is "https://10.27.10.10/redmine" for me and redmineKey is my redmine API key
RedmineManager redmineManager = new RedmineManager(redmineURL, redmineKey);
// Create your query parameters
NameValueCollection queryParameters = new NameValueCollection { { "project_id", "4" }, {"tracker_id", "17"}, { "offset", "0" } };
// Perform your query
int issuesFound = 0;
foreach (var issue in redmineManager.GetObjectList<Issue>(queryParameters, out issuesFound))
{
// By default you get the 25 first issues of the project_id and tracker_id specified.
// Play with the offset to get the rest
queryParameters["offset"] = ....
}
Explicit passing SecurityProtocolType.Tls12 value for securityProtocolType parameter solved the problem for my case:
RedmineManager redmineManager = new RedmineManager(_host, _apiKey,
securityProtocolType: SecurityProtocolType.Tls12);
I'm struggling with the final part of getting my first bit of code working with the AWS - I have got this far, I attached the web reference in VS and this have this
amazon.AWSECommerceService service = new amazon.AWSECommerceService();
// prepare an ItemSearch request
amazon.ItemSearchRequest request = new amazon.ItemSearchRequest();
request.SearchIndex = "DVD";
request.Title = "scream";
request.ResponseGroup = new string[] { "Small" };
amazon.ItemSearch itemSearch = new amazon.ItemSearch();
itemSearch.AssociateTag = "";
itemSearch.Request = new ItemSearchRequest[] { request };
itemSearch.AWSAccessKeyId = ConfigurationManager.AppSettings["AwsAccessKeyId"];
itemSearch.Request = new ItemSearchRequest[] { request };
ItemSearchResponse response = service.ItemSearch(itemSearch);
// write out the results
foreach (var item in response.Items[0].Item)
{
Response.Write(item.ItemAttributes.Title + "<br>");
}
I get the error
The request must contain the parameter Signature.
I know you have to 'sign' requests now, but can't figure out 'where' I would do this or how? any help greatly appreciated?
You have to add to the SOAP request headers including your Amazon access key ID, a timestamp, and the SHA256 hash of the request operation and the timestamp. To accomplish that, you would need access to the SOAP message just before it is going to be sent out. There's a walkthrough and a sample project I put together at http://flyingpies.wordpress.com/2009/08/01/17/.
For the record:
Another reason to get this error is due to keywords with spaces in it.
Example:
'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=xxx&AssociateTag=usernetmax-20&Version=2011-08-01&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=All&Keywords=Baby
Stroller&MerchantId=All&Condition=All&Availability=Available&ItemPage=1&Timestamp=2012-05-16T02:17:32Z&Signature=ye5c2jo99cr3%2BPXVkMyXX8vMhTC21UO4XfHpA21%2BUCs%3D'
It should be:
'http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=xxx&AssociateTag=usernetmax-20&Version=2011-08-01&Operation=ItemSearch&ResponseGroup=Medium,Offers&SearchIndex=All&Keywords=Baby%20Stroller&MerchantId=All&Condition=All&Availability=Available&ItemPage=1&Timestamp=2012-05-16T02:17:32Z&Signature=ye5c2jo99cr3%2BPXVkMyXX8vMhTC21UO4XfHpA21%2BUCs%3D'
PHP solution:
$Keywords = str_replace(' ', '%20', $Keywords);
or
$Keywords = urlencode($Keywords);
I try to implement simple SOAP server on ASP.NET and simple client on php and get the problem with response and request format.
My server is very simple, take one string and return another:
[WebMethod]
public string HelloWorld(string Additional) {
return "Hello " + Additional;
}
I expect, that php client is such simple:
$client = new SoapClient('path');
print_r($client->HelloWorld('homm'));
Hello homm
But actually, function take only objects and return object with single member — HelloWorldResult:
$client = new SoapClient('path');
print_r($client->HelloWorld(array('Additional' => 'homm')));
stdClass Object
(
[HelloWorldResult] => Hello homm
)
Can I change this behavior? What part I need to change, server (ASP.NET) or client(php) to work with results and parameters indirect?