Skip to content

Instantly share code, notes, and snippets.

@bjhaid
Created April 9, 2015 18:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bjhaid/5d3c58aca0dbee0d96fd to your computer and use it in GitHub Desktop.
Save bjhaid/5d3c58aca0dbee0d96fd to your computer and use it in GitHub Desktop.
-module(isbn).
-export([generate_signed_url/2]).
%%http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html
generate_signed_url(Secret, Url) -> [H, T] = sort_url_params(append_timestamp(Url)),
H ++ "?" ++ T ++ "&Signature=" ++ hash_url_params(Secret, prepend_request_header(T)).
encode_url(Url) -> http_uri:encode(Url).
iso8601utctime() -> [{{Year,Month,Day},{Hour,Min,Sec}}] = calendar:local_time_to_universal_time_dst(calendar:local_time()),
IODataTime = io_lib:fwrite("~B-~2.10.0B-~2.10.0BT~2.10.0B:~2.10.0B:~2.10.0BZ", [Year,Month,Day,Hour,Min,Sec]), erlang:binary_to_list(erlang:iolist_to_binary(IODataTime)).
%% Replace with:
%% URL ++ "&Timestamp=2014-08-18T12:00:00Z".
%% to test sample
append_timestamp(URL) -> URL ++ "&Timestamp=" ++ iso8601utctime().
sort_url_params(URL) ->
[H, ReqParam] = string:tokens(URL, "?"),
L = lists:map(fun(X) -> [L1, L2] = string:tokens(X, "="), L1 ++ "=" ++ encode_url(L2) end, string:tokens(ReqParam, "&")),
[H, string:join(lists:sort(L), "&")].
prepend_request_header(URL) -> "GET\nwebservices.amazon.com\n/onca/xml\n" ++ URL.
hash_url_params(Secret, Str) -> encode_url(base64:encode_to_string(crypto:hmac(sha256, Secret, list_to_binary(Str)))).
%% Example
%% isbn:generate_signed_url("1234567890", "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&AssociateTag=mytag-20&Operation=ItemLookup&ItemId=0679722769&ResponseGroup=Images,ItemAttributes,Offers,Reviews&Version=2013-08-01").
%% "http://webservices.amazon.com/onca/xml?AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&AssociateTag=mytag-20&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=Images%2CItemAttributes%2COffers%2CReviews&Service=AWSECommerceService&Timestamp=2014-08-18T12%3A00%3A00Z&Version=2013-08-01&Signature=j7bZM0LXZ9eXeZruTqWm2DIvDYVUU3wxPPpp%2BiXxzQc%3D"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment