繁体   English   中英

无法使用PHP和Curl连接到Microsoft Dynamics CRM

[英]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_typeclient_idclient_secretresource并且grant_type值为client_credentials

资源所有者的密码凭据流需要grant_typeclient_idclient_secretusernamepasswordresource并且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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM