I am trying to use python requests to receive my access token for the Amazon Advertising API. The procedure is outlined here: https://advertising.amazon.com/API/docs/v2/guides/authorization Here is what I tried
CLIENT_ID = MyClientID
CLIENT_SECRET = MySecret
RETURN_URL = 'https://myreturn.com/my.php'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.61 Safari/537.36',
}
with requests.Session() as s:
s.headers = headers
r = s.get('https://www.amazon.com/ap/oa?client_id={}&scope=cpc_advertising:campaign_management&error=access_denied&response_type=code&redirect_uri={}'.format(CLIENT_ID,RETURN_URL),headers=headers)
soup = BeautifulSoup(html)
data = {}
form = soup.find('form', {'name': 'signIn'})
for field in form.find_all('input'):
try:
data[field['name']] = field['value']
except:
pass
data[u'email'] = MY_EMAIL
data[u'password'] = MY_PASS
b = s.post('https://www.amazon.com/ap/oa?client_id={}&scope=cpc_advertising:campaign_management&response_type=code&redirect_uri={}',data=data,allow_redirects=True,headers=headers)
i get an error_description=User+not+authenticated&error=access_denied error, what am I doing wrong here?
解决方案
You DON'T NEED Username and Password in your Python Script to authenticate!
What you need is CLIENT_ID, SCOPE and REDIRECT_URI and three requests:
Get authorization code:
GET https://www.amazon.com/ap/oa?client_id={{CLIENT_ID}}&scope={{SCOPE}}&response_type=code&redirect_uri={{REDIRECT_URI}}
This will open the 'Login with Amazon' Consent Page, where you (or your customer) log into your Amazon Seller Central account and grant access to the Console APP with API access rights.
Request tokens
POST https://api.amazon.com/auth/o2/token
with headers:
Content-Type:application/x-www-form-urlencoded
with body data:
grant_type:authorization_code
code:{{AUTH_CODE}}
client_id:{{CLIENT_ID}}
client_secret:{{CLIENT_SECRET}}
redirect_uri:{{REDIRECT_URI}}
Get/Refresh access token (every time it is outdated):
POST https://api.amazon.com/auth/o2/token
with headers:
Content-Type:application/x-www-form-urlencoded
charset:UTF-8
with body data:
grant_type:refresh_token
refresh_token:{{REFRESH_TOKEN}}
client_id:{{CLIENT_ID}}
client_secret:{{CLIENT_SECRET}}
With the CLIENT_ID and (fresh) access token you can now request every service from the API. For excample listCampaigns:
GET https://advertising-api.amazon.com/v2/sp/campaigns
Headers:
Content-Type:application/json
Amazon-Advertising-API-ClientId:{{CLIENT_ID}}
Amazon-Advertising-API-Scope:{{PROFILE_ID}}
Authorization:Bearer {{ACCESS_TOKEN}}