11/18/2016

WooCommerce API Using RestSharp Over HTTP With OAuth

Now after searching NuGet I saw that there is a C# WooCommerce library out there all ready written called WooCommerce.NET. This isn’t going to work for me because I will need the ability to gain access to custom Order fields.

So I decided to just use my favorite REST client RestSharp to contact a fairly simple REST API for WooCommerce. But I was running into a strange authentication issue and being denied authentication with a 401 status code.

Now, first a disclaimer… DO NOT USE HTTP FOR WooCommerce IN A PRODUCTION ENVIRONMENT!

Ok, but I need to do some testing in a local environmnet so I can see that my code is working properly. Reading the WooCommerce documentation for authentication, which can be found here, it clearly states:

The OAuth parameters must be added as query string parameters and not included in the Authorization header. This is because there is no reliable cross-platform way to get the raw request headers in WordPress.

So I do a bit of digging about RestSharp and OAuth1.0 and come up with this suite of tests. Here’s the important bit that I needed:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
[Test]
public void Can_Authenticate_OAuth1_With_Querystring_Parameters()
{
const string consumerKey = "enterConsumerKeyHere";
const string consumerSecret = "enterConsumerSecretHere";
const string baseUrl = "http://restsharp.org";
var expected = new List<string>
{
"oauth_consumer_key",
"oauth_nonce",
"oauth_signature_method",
"oauth_timestamp",
"oauth_version",
"oauth_signature"
};

RestClient client = new RestClient(baseUrl);
RestRequest request = new RestRequest(Method.GET);
var authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
authenticator.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;
authenticator.Authenticate(client, request);

var requestUri = client.BuildUri(request);
var actual = HttpUtility.ParseQueryString(requestUri.Query).AllKeys.ToList();

Assert.IsTrue(actual.SequenceEqual(expected));
}

The above Authenticate method will do all the work and add all the parameters I need.

But wait… Something’s not right here. In the debugger it shows me that the parameters on the request are being added as cookes:

Visual Studio Debugger

Strange, but ok. So I decided to make an extension method that does all the authentication, gets all the parameters added to the request, and then converts them to QueryString parameters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static class RestRequestExtensions
{
public static RestRequest BuildOAuth1QueryString(this RestRequest request, RestClient client, string consumerKey, string consumerSecret)
{
var auth = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret);
auth.ParameterHandling = OAuthParameterHandling.UrlOrPostParameters;
auth.Authenticate(client, request);

//convert all these oauth params from cookie to querystring
request.Parameters.ForEach(x =>
{
if (x.Name.StartsWith("oauth_"))
x.Type = ParameterType.QueryString;
});

return request;
}
}

So the code to build a request now looks something like this.

1
2
3
4
var client = new RestClient("http://example.com/api/v1");
var request = new RestRequest("/path/to/resource");
request.BuildOAuth1QueryString(client, "{consumer_key}", "{consumer_secret}");
var response = client.Execute(request);

And there we have it. Talking to WooCommerce with RestSharp.

For Production

I can not stress enough to not communicate over HTTP in production. In production, you should be using HTTPS. In that case you can use HTTP Basic Authentication. Then you will no longer need the BuildOAuth1QueryString extension method, you would simply add the Basic Authentication to the client like so:

1
2
//Basic over Https
client.Authenticator = new HttpBasicAuthenticator("{consumer_key}", "{consumer_secret}");

Hope this helps!

View Comments
11/17/2016

The Developer's Feed

Every day in the ever changing world of technology and development, I try to do some reading to keep up with the world around me. I have worked in places with small teams and big teams, but my current situation puts me as the only person with development skills in my current company. It’s really important in this situation, not to lose touch with the world of development around you. This feed has kept me up to date with new tech and also taught me even more about tech I all ready thought I knew.

I’ve been curating this list of blog feeds since I became a developer a long time ago, so many of them may be out-dated. Still, there are always great articles popping up for me to read and dabble in the tech if I have the time. Personally I use Feedly for my RSS reader, but the file should easily import into your favorite RSS reader.

Developer Feed File - You may need to Right Click -> Save As

Anyhow, hope you enjoy!

View Comments
11/16/2016

The Need to Knows of Developers

I was talking to a friend the other day about what you need to know to be an effective developer. We touched on topics like source control, people skills, presentation skills and a ton of other skills that are inherent things that are need to know. Other things could include frameworks, good blog sites, or how to get what you’re asking for from your boss. After a while we got into the code aspect of being a developer. Where do you start? What is a waste of time to learn? When should I know what? Well, I certainly don’t know the best way but I’ll share the order that worked for me.

Let’s just start basic. The first thing you should know about developing for whatever it is you want to write code for is the syntax of the language you’ll be using. Start simple, think “Hello World”.

If you’re learning an Object Oriented language (like C#), your next stop should be The four pillars of Object Oriented Design

  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation

Once you have an understanding of the 4 pillars in my opinion your next stop should be learning the SOLID principles

  • Single responsibility principle
  • Open/closed principle
  • Liskov substitution principle
  • Interface substitution principle

Once you’ve gotten to principles you can start to make more maintainable code in larger projects.

Finally, once you’ve gotten those down it’d be best to look into the Gang of Four Design Patterns. These are proven patterns for enterprise scale production systems. If you have a good understanding of the problem you’re trying to solve, there’s a good chance a combination of these patterns will help you solve it.

All of this being said, there are problems you come across time and again as a developer. One of the biggest ones I face often is that of cross cutting concerns. I have this thing that does one thing, but now needs to do another. For example, you have data going into a database and you’d like to audit who put the record in with some sort of logging. In this case there are many solutions, and you could even write your own using all those spiffy patterns. Or in my case I found a great library called MediatR that implements a nice architecture solving that problem for me. Sometimes with the right amount of digging you’ll find a good library that solves the recurring problems.

Update

It is almost imperative now to know about cloud architecture for hightly available and scalable applications. I had the pleasure of reconnecting with a former colleague of mine who so happens to be a cloud architect at Microsoft. He pointed me toward his GitHub for some guidance on Microsoft Azure cloud architecture. You can see the repository on his GitHub here.

Happy coding!

View Comments
11/15/2016

Blog Up and Running With Hexo!

I’ve been working with a lot of NodeJS stuff lately in my off time using things like Bower, Grunt, Gulp, etc… It’s been a nice break from my usual .NET stuff. It’s been a long while since I had my site up, running and full functional with a blog and everything. I’m not sure how much I’ll use it, but I used to put a lot of time and energy into blog posts. Maybe I’ll see if I can recover those old posts somehow. But for now I’m up and running with GitHub Pages and Hexo.

You can find more about hexo at http://hexo.io

Update

I was able to get some, but not all of my old posts back. It took a lot of digging and code re-formatting but it was worth it. Took some time learning EJS and Hexo template stuff, but the site is looking nice.

View Comments