使用恒定联系 API

问题描述

我正在尝试使用 Python 和 Constant Contact API 将新联系人推送到 Constant Contact 并将它们添加到列表中。到目前为止,我已经尝试了以下方法

import requests

url = 'https://api.cc.email/v3/contacts'
url_completed = url + '?api_key=' + api_key

post_request = {
    "email_address": {
        "address": "abc123@gmail.com"
    },"first_name": "First","last_name": "Last","create_source": "Account","list_memberships": ["xxxxxxxxx"]
}

headers = {
    'Authorization': 'Bearer xxxxxxx','content_type': 'application/json'
}

resp = requests.post(url_completed,data=post_request,headers=headers)
print(resp.raise_for_status())

但是当我运行这个时,我得到一个错误 401 Client Error: Unauthorized for url: https://api.cc.email/v3/contacts?api_key=xxxxxxx

为什么我会收到这个错误?为了确保我正确执行此操作,需要更多背景知识,我进入了 Constant Contact dev portal 并创建了一个新应用程序。它给了我一个 API 密钥,我将其插入到 URL 中,以及一个秘密,我认为它是不记名令牌,因此将其替换在那里。我还使用 Constant Contact 参考文档 UI 测试了有效负载,该 UI 允许在 OAuth 身份验证后测试有效负载,并且成功了。具体来说,我使用的是 this endpoint

解决方法

401 表示“访问令牌无效”。很可能,您不能使用应用程序提供的 API 密钥,而是使用 OAuth 2.0 流程提供的专用访问令牌。详细了解 OAuth 授权 here