簡體   English   中英

使用PHP在MS Dynamics中使用訪問令牌訪問Web API

[英]Access web api using access token in MS Dynamics using php

對於有關Azure帳戶的上一個問題 ,我可以使用azure帳戶創建一個應用。

現在,我可以從以下網址獲取身份驗證代碼: Auth_code

從Auth_code中,我們可以通過以下方式獲取訪問令牌:

  $auth_code = $_GET['code'];
  $result = access($auth_code);


   function access($auth_code){
        $redirectUri = 'https://XXXX /authorize.php';


    $token_request_data = array (
    "grant_type" => "authorization_code",
    "code" => $auth_code,
    "redirect_uri" => $redirectUri,
    "client_id" => "client_id",
    "client_secret" => "client_secret",
    "resource" =>"resource" (From manifest in azure)
  );


  $token_request_body = http_build_query ( $token_request_data );


   $curl = curl_init ( 'https://login.windows.net/common/oauth2/token' );
   curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, true );
   curl_setopt ( $curl, CURLOPT_POST, true );
   curl_setopt ( $curl, CURLOPT_POSTFIELDS, $token_request_body );
   curl_setopt ( $curl, CURLOPT_SSL_VERIFYPEER,false);

    $response = curl_exec ( $curl );

    $res = json_decode($response);
    curl_close ( $curl );

現在,我嘗試使用該access_token訪問Web api,但無法獲得結果。 例如:

 $authHeader = 'Authorization:Bearer access_toke';
 $ch = curl_init();
 $url = 'https://domain/api/data/v8.0/contacts';
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
 curl_setopt($curl, CURLOPT_POST, false);
 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_URL, $url);
 curl_setopt($curl, CURLOPT_HTTPHEADER, array($authHeader, 'Content-  Type:application/json'));
 $result = curl_exec($curl);
  echo "<pre>";print_r($result);exit;
 curl_close($curl);

我的回應是空的。 現在,我必須知道如何使用訪問令牌訪問Web API。

當我嘗試手動運行https://domain/api/data/v8.0/contacts ,我可以在我的crm中獲取所有聯系人。但是當我嘗試使用php通過access_token訪問它時,它返回為空。

Web API參考URLWeb API URL的 參考

請參閱指南撰寫HTTP請求和處理錯誤 ,如HTTP標頭部分所示的要求:

每個請求都應包括application / json的Accept標頭值,即使沒有響應主體也是如此。

在PHP腳本中, curl_setopt($curl, CURLOPT_HTTPHEADER, array($authHeader, 'Content- Type:application/json')); 您可以刪除Content-Type中的空格,然后重試。

順便說一下,您可以利用Fiddler捕獲來自PHP客戶端的請求。 我們通過該工具獲得響應正文內容並請求狀態代碼。 我們可以在https://msdn.microsoft.com/zh-cn/library/gg334391.aspx#bkmk_statusCodes上將狀態代碼與列表進行匹配。 如果代碼始終為200而沒有響應主體,則可以在Web api中檢查代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM