[英]Unable to connect to Microsoft Dynamics CRM with PHP and Curl
我正在嘗試使用PHP和CURL連接到Microsoft Dynamics API,以便可以從CRM中讀取客戶端數據。 可以在以下位置找到API指南: https : //msdn.microsoft.com/en-gb/library/mt593051.aspx
我去過Azure門戶並設置了一個新應用程序,它為我提供了要使用的憑據(客戶端ID,機密等)和url端點。 使用這些憑據,我能夠成功連接到CRM並檢索承載訪問令牌,但是我無法獲得進一步的信息。
當我嘗試使用令牌返回數據時,收到以下錯誤消息:
HTTP錯誤401-未經授權:訪問被拒絕
我的假設是我必須正確傳遞令牌?
我的代碼如下。
<?php
// Step 1 - Use the credentials supplied by CRM to get an access token (this bit works okay)
$credentials = array(
'grant_type'=>'client_credentials',
'username'=>'xxxxxxxx',
'password'=>'xxxxxxxx',
'client_id'=>'xxxxxxxxxxxx',
'client_secret'=>'xxxxxxxxxx',
);
$urlSafeCredentials = http_build_query($credentials);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://login.microsoftonline.com/xxxxxxxxxxxxxx/oauth2/token');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $urlSafeCredentials);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch);
// A BEARER access token is successfully returned
$token = $result->access_token;
// Step 2 - Use the access token to request data from the CRM (this bit fails with HTTP Error 401 - Unauthorized: Access is denied)
$ch = curl_init('https://clientspecificurl.crm4.dynamics.com/api/data/v8.1/accounts');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/x-www-form-urlencoded','Authorization: Bearer '.$token));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
print_r($response); // 401 Unauthorized ?!
?>
據我所知,在后端沒有其他可配置的內容,我們將不勝感激。
根據獲取令牌的參數,您正在混合客戶端憑據流和資源所有者密碼流以及缺少resource
參數。
客戶端憑證流需要參數grant_type
, client_id
, client_secret
, resource
並且grant_type
值為client_credentials
。
資源所有者的密碼憑據流需要grant_type
, client_id
, client_secret
, username
, password
, resource
並且grant_type
值為password
。
如果使用的是客戶憑證流,則可以參考此博客以獲取令牌。 如果使用的是資源所有者密碼 ,則可以引用此線程 。
有關Oauth 2中流程差異的詳細信息,請參閱RFC 6749 。
我編寫了一個輕量級的PHP類,用於使用Dynamics 365在線Web API。 你可以在這里找到它。
順便說一句,在您的代碼中,您應該嘗試在Grant_type內嘗試使用“ password”而不是“ client_credentials”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.