gpt4 book ai didi

python - 向 Dynamics CRM Web API 发出请求

转载 作者:行者123 更新时间:2023-12-01 03:22:37 26 4
gpt4 key购买 nike

我正在尝试创建一个应用程序,使用 urllib2 从 python 向 Dynamics CRM Web API 发出请求。到目前为止,我可以通过向 https://login.microsoftonline.com/common/oauth2/authorize 发出发布请求来使用 Azure 应用程序登录用户。然后通过检索到的authorization_code,我可以使用urllib2获取access_token、refresh_token等

url = 'https://login.microsoftonline.com/common/oauth2/token'
post_fields = {'grant_type': 'authorization_code',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'resource': 'https://graph.microsoft.com',
'code': code}
request = Request(url, urlencode(post_fields).encode())
resp = urlopen(request).read().decode()
resp = json.loads(resp)
refresh_token = resp['refresh_token']
id_token = resp['id_token']
id_token = jwt.decode(id_token,verify=False)
access_token = resp['access_token']

然后我尝试使用 access_token 发出另一个 post 请求,但没有成功。我不断得到:

HTTP Error 401: Unauthorized

作为测试,我直接在 .dynamics.com/api/data/v8.1/leads 上发帖如下:

url = 'https://<company_uri>.dynamics.com/api/data/v8.1/leads'
post_fields = {"name": "Sample Account",
"creditonhold": "false",
"address1_latitude": 47.639583,
"description": "This is the description of the sample account",
"revenue": 5000000,
"accountcategorycode": 1
}
request = Request(url, urlencode(post_fields).encode())
request.add_header('Authorization', 'Bearer ' + access_token )
request.add_header("Content-Type", "application/json; charset=utf-8")
request.add_header('OData-MaxVersion','4.0')
request.add_header('OData-Version','4.0')
request.add_header('Accept','application/json')
resp = urlopen(request).read().decode()

但我不断收到相同的 401 错误代码。我查遍了 msdn 文档,但没有找到不使用任何库直接执行此操作的方法,我只想使用一个简单的 post 请求。

由于错误代码显示未经授权,我认为 access_token 必须以其他方式发送。有人可以帮助我如何在 Dynamics CRM 上正确使用 access_token 吗?谢谢!

最佳答案

您取回的访问 token 用于 Azure AD Graph API。不是 Dynamics CRM。

要调用它,您必须请求访问 token ,并将资源设置为 Dynamics CRM API 的应用程序 ID URI,而不是 https://graph.windows.net .

根据documentation您应该将资源设置为https://<company_uri>.crm.dynamics.com .

因此,当您检索 token 时:

url = 'https://login.microsoftonline.com/common/oauth2/token'
post_fields = {'grant_type': 'authorization_code',
'client_id': CLIENT_ID,
'client_secret': CLIENT_SECRET,
'redirect_uri': REDIRECT_URI,
'resource': 'https://<company_uri>.crm.dynamics.com',
'code': code}

关于python - 向 Dynamics CRM Web API 发出请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41786709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com