I’ve been working on the basis for a shopping cart example using the Amazon.com RESTful API and Silverlight 2 for my book. Their API is pretty extensive and the documentation is top notch. Its amazing how much more effective developers can be with good documentation. The application allows the user to search for items, create a shopping cart and add/remove the items in a Silverlight UI. Its pretty cool and obviously can be extended quite a bit. Here’s a glimpse of the app where I added Julie Lerman’s book and my Data Services with Silverlight 2 book to the cart, while shopping for some other items.
I ran into a problem along the way where I could not get the shopping cart code passed and URL encoded properly. The code is called an HMAC code and Amazon uses it as a key value for the cart identification along with a Cart Id. The HMAC may contain the + sign. Aha, you say … there’s the rub. The + sign must be encoded to %2B. Even Amazon’s documentation reinforces this. However simply encoding the + to %2B is not enough. (2b or not 2b? … lol) When I did this and watched the request fly off to Amazon (watching it through Fiddler2) the url contained a + again! Amazon returned a response alright, but it contained an error about the invalid HMAC.
The solution was that I had to double encode it! I used the HttpUtility.UrlEncode method to do the job and since I was in Silverlight there were limited options since I did not have the entire CLR at my disposal. So I had to encode the + to a %2B and then again to a %25B. Then I watched it fly off to Amazon and all was well.
So the lesson in the story is that in Silverlight if you need to pass a + in a parameter of a Uri then you should double UrlEncode it. Amazon returns a URLEncodedeHMAC in the response (after you create a cart) so I grabbed that and encoded it once. The other option is to grab the un-encoded HMAC and double encode it.
Oh, and no, I am not going to ship my codes and IDs with the final solution in the book. I don’t want everyone buying stuff from Amazon on my tab!