【问题标题】:Unable to connect to Microsoft Dynamics CRM with PHP and Curl无法使用 PHP 和 Curl 连接到 Microsoft Dynamics CRM
【发布时间】:2017-10-19 21:13:37
【问题描述】:

我正在尝试使用 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 ?!
?>  

据我所知,后端无需配置任何其他内容,我们将不胜感激。

【问题讨论】:

    标签: php curl dynamics-crm azure-active-directory microsoft-dynamics


    【解决方案1】:

    根据获取令牌的参数,您混合了客户端凭据流资源所有者密码流,并且缺少resource 参数。

    客户端凭据流需要参数grant_type,client_id,client_secret,resourcegrant_type 的值为client_credentials

    资源所有者密码凭证流程需要grant_type,client_id,client_secret,username,password,resourcegrant_type 的值为password

    如果您使用的是客户端凭据流程,您可以参考 this blog 获取令牌。如果您使用的是资源所有者密码,您可以参考this thread

    Oauth 2 中的流量差异详情请参考RFC 6749

    【讨论】:

      【解决方案2】:

      我编写了一个用于处理 Dynamics 365 在线 Web API 的轻量级 PHP 类。你可以找到它here

      顺便说一句,在您的代码中,您应该在grant_type 中尝试“password”而不是“client_credentials”

      【讨论】:

        猜你喜欢
        • 2016-12-03
        • 1970-01-01
        • 1970-01-01
        • 2011-12-17
        • 2010-11-10
        • 2011-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多