I have successfully implemented a one time pass through MailChimp's (MC) six step OAuth2 process, documented at http://apidocs.mailchimp.com/oauth2/, using Python and Django. The problem is I want my users to be able to authorize MC once and then I will use that authorization to make calls to MC in the future (with their permission, of course).
Here's how I am doing it:
Step 1: Redirect use to the MC authorize URI.
(works fine)
Step 2: User enters their MC credentials.
(works fine)
Step 3: User gets redirected back to a URI on my server, and
Step 4: I make a request to the MC access token URI, and
Step 5: MC returns an access token.
headers = {
'User-Agent': 'oauth2-draft-v10',
'Content-Type': 'application/x-www-form-urlencoded',
'Host': 'login.mailchimp.com',
'Accept': 'application/json'
}
payload = {
'grant_type': 'authorization_code',
'client_id': settings.MAILCHIMP_CLIENT_ID,
'client_secret': settings.MAILCHIMP_CLIENT_SECRET,
'code': code,
'redirect_uri': settings.MAILCHIMP_REDIRECT_URI
}
response = requests.post(settings.MAILCHIMP_ACCESS_TOKEN_URI, headers=headers, data=payload)
response_dict = response.json()
access_token = response_dict['access_token']
At this point I save the access_token, the datacenter-less API key, in my database.
Step 6: I make a request to the MC metadata URI to get a datacenter.
Note that this step occurs multiple times as I need to make MC calls on the user's behalf, whereas Steps 1-5 only occur once.
headers = {'Authorization': 'OAuth ' + access_token}
response = requests.get(settings.MAILCHIMP_METADATA_URI, headers=headers)
response_dict = response.json()
dc = response_dict['dc']
Step 7: I construct an API key and make MC calls using the Python library.
mkey = access_token + '-' + dc
mcapi = mailchimp.Mailchimp(apikey=mkey)
mcapi.do_something_fun_with_mailchimp()...
The problem is that the final step intermittently returns the error,
Invalid Mailchimp API Key: <key>-dc
. You are accessing the wrong datacenter - your client library may not properly support our datacenter mapping scheme.
What am I doing wrong?