Skip to content

Instantly share code, notes, and snippets.

@rafaelhdr
Last active August 29, 2015 14:22
Show Gist options
  • Save rafaelhdr/834a0d39f23ac3b6d6aa to your computer and use it in GitHub Desktop.
Save rafaelhdr/834a0d39f23ac3b6d6aa to your computer and use it in GitHub Desktop.
Generate signed URL for Amazon Associates
from time import gmtime, strftime
import urllib2
import hmac
import hashlib
import base64
"""
Code to generate signed URL for Amazon Associate
I hope it is simple to understand
Don't forget to fill PUBLICKEY, SECRETKEY and ASSOCIATETAG
And also edit HOST and SEARCH
Good links
http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html
http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html
Amazon hash help from stackoverflow
http://stackoverflow.com/questions/1306550/calculating-a-sha-hash-with-a-string-secret-key-in-python
"""
# Keys
# Get AWS Security Credentials
# http://docs.aws.amazon.com/general/latest/gr/getting-aws-sec-creds.html
# Access keys (access key ID and secret access key)
PUBLICKEY = ""
SECRETKEY = ""
# Associate tag
ASSOCIATETAG = ""
# Host
HOST = 'webservices.amazon.com.br'
# Search term example
SEARCH = urllib2.quote("Harry Potter")
# Example data
time = strftime("%Y-%m-%dT%H:%M:%SZ", gmtime())
response_group = 'Large,EditorialReview,ItemAttributes,OfferFull,Offers'
# Unsigned URL
uri = 'Operation=ItemSearch&Condition=All&Availability=Available'
uri += '&ResponseGroup=' + urllib2.quote(response_group)
uri += '&Version=2011-08-01'
uri += '&Keywords=' + SEARCH
uri += '&SearchIndex=Books'
uri += "&AWSAccessKeyId=" + PUBLICKEY
uri += "&AssociateTag=" + ASSOCIATETAG
uri += "&Timestamp=" + urllib2.quote(time)
uri += "&Service=AWSECommerceService"
uri += "&Sort=relevancerank"
unsigned_url = "http://webservices.amazon.com.br/onca/xml?" + uri
# Signed URL
parameters = uri.split('&')
parameters.sort()
sorted_pairs = "\n".join(list(parameters))
uri = '&'.join(parameters)
get_request = """GET
%s
/onca/xml
%s""" % (HOST, uri)
string_to_sign = get_request
# Hash for Signature
dig = hmac.new(SECRETKEY, msg=get_request, digestmod=hashlib.sha256).digest()
signature = base64.b64encode(dig).decode()
signature = urllib2.quote(signature, '')
uri = "http://webservices.amazon.com.br/onca/xml?" + uri
uri += "&Signature=" + signature
signed_url = uri
# Data created
# Compare at
# http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html
print "\nunsigned url"
print unsigned_url
print "\nsorted pairs"
print sorted_pairs
print "\nstring to sign"
print string_to_sign
# The most useful data
print "\nsigned url"
print signed_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment