none
Connect to CRM using nuSOAP from PHP server to create new entity.

    질문

  • Hello Microsoft gurus, I have a huge question I've been working on for the last 3 days.

    I have a site running on PHP. We have contact form there. We need to create new case in our CRM once the person fills and submits that form.

    I am not able to bypass the NTLM authorisation and I getthis response.
    soap_transport_http: Got 401 Unauthorized with WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAwADADgAAAAGgokCStRMi8kLYbsAAAAAAAAAAIIAggA7AAAABQLODgAAAA9NU0gCAAYATQBTAEgAAQAWAEEAUABSAE0ATgBHAFAAUgBEADAAMgAEABIAbQBzAGgALgBsAG8AYwBhAGwAAwAqAEEAUABSAE0ATgBHAFAAUgBEADAAMgAuAG0AcwBoAC4AbABvAGMAYQBsAAUAEgBtAHMAaAAuAGwAbwBjAGEAbAAAAAAA
    This one is type-3 NTLM auth message - meaning I am actually calling the server and giving him some credentials but he doesn't recognise me. I have a local copy of WSDL file so I can read all the operations from there without authorisation but I cannot send my request to the CRM server to create new entity.

    Here is my PHP code

    <?php
    require_once('nusoap/nusoap.php');
    
    $login ='MSH\dpavluchkov_johnva.r'; // domain login name
    $login ='dpavluchkov@johnva.ru'; // crm login name
    $pass ='password';
    $useCURL = 1;
    
    $client = new nusoap_client("http://6.jvatv.ru/CrmServiceWsdl.aspx", 'wsdl');
    $client->setCredentials($login, $pass, 'ntlm');
    $err = $client->getError();
    if ($err) {
    echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
    echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
    exit();
    }
    $client->setUseCurl($useCURL);
    $client->useHTTPPersistentConnection();
    
    // Prepare values for the new contact.
    $firstname = "112";
    $lastname = "123";
    $donotbulkemail = "true";
    $address1_stateorprovince = "MT";
    $address1_postalcode = "99999";
    $address1_line1 = "23 Market St.";
    $address1_city = "Sammamish";
    
    // This exact header was recieved from GenerateAuthenticationHeader() JScript function.
    $authenticationHeader = '<soap:Header><CrmAuthenticationToken xmlns=“http://schemas.microsoft.com/crm/2007/WebServices“><AuthenticationType xmlns=“http://schemas.microsoft.com/crm/2007/CoreTypes“>2</AuthenticationType><OrganizationName xmlns=“http://schemas.microsoft.com/crm/2007/CoreTypes“>Johnva</OrganizationName><CallerId xmlns=“http://schemas.microsoft.com/crm/2007/CoreTypes“>00000000-0000-0000-0000-000000000000</CallerId></CrmAuthenticationToken></soap:Header>';
    
    // Prepare the SOAP message.
    $xml = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" .  $authenticationHeader . "<soap:Body><Create xmlns='http://schemas.microsoft.com/crm/2007/WebServices'><entity xsi:type='contact'><address1_city>" . $address1_city . "</address1_city>" .  "<address1_line1>" . $address1_line1 . "</address1_line1>" .  "<address1_postalcode>" . $address1_postalcode . "</address1_postalcode>" .  "<address1_stateorprovince>" . $address1_stateorprovince . "</address1_stateorprovince>" .  "<donotbulkemail>" . $donotbulkemail . "</donotbulkemail>" .  "<firstname>" . $firstname . "</firstname>" .  "<lastname>" . $lastname . "</lastname>" .  "</entity>" .  "</Create>" .  "</soap:Body>" .  "</soap:Envelope>";
    
    $headers = array('SOAPAction' => 'http://schemas.microsoft.com/crm/2007/WebServices/Create', 'Content-Type' => 'text/xml; charset=utf-8', 'Content-Length' => strlen($xml));
    
    $result = $client->call('Create', $xml, 'http://schemas.microsoft.com/crm/2007/WebServices', 'http://schemas.microsoft.com/crm/2007/WebServices/Create', $headers);
    if ($client->fault) {
        echo '<p><b>Fault: ';
        print_r($result);
        echo '</b></p>';
    } else {
        // Check for errors
        $err = $client->getError();
        if ($err) {
            // Display the error
            echo '<p><b>Error: ' . $err . '</b></p>';
            echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
        } else {
            // Display the result
            print_r($result);
        }
    }
    
    var_dump($client->response);    
    
    ?>
    I have few questions here.

    1. Which login name should I use - one that is from my AD or the one I use to login to CRM?
    2. Why my auth header from GenerateAuthenticationHeader() function returned AuthenticationType of 2?
    3. Do you have any ideas why I can get 401 error even when my password and login name is correct?

    I can post debug and response values, they might help you understand the problem a bit further if you need them.


    Thanks,
    Daniel.
    2009년 7월 23일 목요일 오후 9:43

답변

  • The answer to the second question answers the first question.  Authentication Type in CRM is an enumeration:  0 is for Active Directory (on-premise), 1 is for Passport (CRM Online), and 2 is for IFD.  You should use your CRM login, not your AD login to connect to the web services.

    For your third question, the 401 is thrown if the url is incorrect, so make sure you can access the asmx page in Internet Explorer.  If you can't get that far, you'll always receive a 401 through code.
    • 답변으로 표시됨 Jim Glass Jr 2009년 8월 6일 목요일 오후 7:59
    2009년 8월 6일 목요일 오후 3:57

모든 응답

  • Hello,

    I am dealing with the same problem for some time and can not find a solution. Hopefully a MS Guru can support in this thread.

    Thanks.

    vn
    2009년 8월 6일 목요일 오후 3:06
  • The answer to the second question answers the first question.  Authentication Type in CRM is an enumeration:  0 is for Active Directory (on-premise), 1 is for Passport (CRM Online), and 2 is for IFD.  You should use your CRM login, not your AD login to connect to the web services.

    For your third question, the 401 is thrown if the url is incorrect, so make sure you can access the asmx page in Internet Explorer.  If you can't get that far, you'll always receive a 401 through code.
    • 답변으로 표시됨 Jim Glass Jr 2009년 8월 6일 목요일 오후 7:59
    2009년 8월 6일 목요일 오후 3:57
  • Used CRM login, here is my results. Note that I am using auth type 2 - this one GenerateAuthenticationHeader() provided me with.

    If I am trying to connect to WSDL file on my CRM server I get "Error: wsdl error: XML error parsing WSDL from https://@johnva.livecrm.ru/MSCrmServices/2007/CrmService.asmx on line 53: Mismatched tag".

    If I download that file and put it to my local directory near the PHP script - I get "Error: Response not of type text/xml: text/plain".

    And the actual response looks like this:
    HTTP/1.1 200 OK
    Date: Thu, 06 Aug 2009 20:36:36 GMT
    Server: Apache
    Last-Modified: Thu, 23 Jul 2009 11:43:59 GMT
    ETag: "e041d-ce60b-46f5e00ddfdc0"
    Accept-Ranges: bytes
    Content-Length: 845323
    Cache-Control: max-age=1209600
    Expires: Thu, 20 Aug 2009 20:36:36 GMT
    Content-Type: text/plain

    HTTP/1.1 100 Continue

    HTTP/1.1 200 OK
    Date: Thu, 06 Aug 2009 20:36:36 GMT
    Server: Apache
    Last-Modified: Thu, 23 Jul 2009 11:43:59 GMT
    ETag: "e041d-ce60b-46f5e00ddfdc0"
    Accept-Ranges: bytes
    Content-Length: 845323
    Cache-Control: max-age=1209600
    Expires: Thu, 20 Aug 2009 20:36:36 GMT"
    Content-Type: text/plain
    And then goes my exact WSDL file as plain text.

    Any ideas to make that work?

    Thanks.
    2009년 8월 6일 목요일 오후 8:46
  • Judging by the error message, it seems the wsdl you downloaded is not well formed xml.  Open the downloaded wsdl in a browser window and it should point you to the invalid part.  Post the wsdl if you don't see it.
    2009년 8월 6일 목요일 오후 8:50
  • Hi both,

    I' am trying to connect via the AD-Authentication, e.g. using the authentication-type 0.

    During the $result=$client->call(...) nusoap makes 2 connects. (the lines-numbers below are circa, as I added some debugging-lines.)

    connect 1)  getting the WSDL - see nusoap.php, ~ line 7198: this->loadWSDL(). The response for this has the http_code 200

    connect 2) serializing the soap-data and sending the soap-request - see nusoap.php, ~ line 7310 ff:

    // serialize envelope
    $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle);
    ...
    // send
    $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout);

    Nusoap serializes the $xml (=$payload) into another envelope and sends this serialized string. Unfortunately the authentication-token than is NOT part of the header anymore, and the http_code for the connect 2 is 401.

    So I do a connect without the serizalized string, instead I use the $payload which contains my $xml. I changed the connect 2) and established successfully a connection. My changed soap-send is like this:

    ...
    //send
    $return = $this->send($this->getHTTPBody($payload),$soapAction,$this->timeout,$this->response_timeout);

    With this, the CRM-access worked fine and new contacts are created. Hopefully, other requests will also work ...

    Kind regards,

    vn
    2009년 8월 10일 월요일 오전 9:06
  • Hello, can you please post the code you used to create contacts? I think with that I might be able to make my script work as well.
    2009년 8월 14일 금요일 오전 11:59
  • My code is like this:

    <?php
     require_once ('../vn/nusoap/lib/nusoap.php');

    //configuration
        $your_organization='XXXXX';
        $login ='domain\domainuser';
        $pass ='password';
        $useCURL = true;

        $client = new nusoap_client('http://crmtest/MSCrmServices/2007/CrmServiceWsdl.aspx?uniquename='.$your_organization, 'wsdl');
        $client->setCredentials($login, $pass, 'ntlm');
        $client->setUseCurl($useCURL);
        $client->useHTTPPersistentConnection();
        $client->soap_defencoding = 'UTF-8';

        $err = $client->getError();
        if ($err) {
            echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
            echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
            exit();
        }

    //create contact
        $soapHeader='<soap:Header>' .
            '<CrmAuthenticationToken xmlns="http://schemas.microsoft.com/crm/2007/WebServices">' .
                '<AuthenticationType xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">0</AuthenticationType>' .
                '<OrganizationName xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">'.$your_organization.'</OrganizationName>' .
                '<CallerId xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">00000000-0000-0000-0000-000000000000</CallerId>' .
            '</CrmAuthenticationToken>' .
            '</soap:Header>';
     
        $soapBody='<soap:Body>' .
            '<Create xmlns="http://schemas.microsoft.com/crm/2007/WebServices">' .
            '<entity xsi:type="contact">' .
                '<address1_city>Sammamish</address1_city>' .
                '<address1_line1>23 Market St.</address1_line1>' .
                '<address1_postalcode>99999</address1_postalcode>' .
                '<address1_stateorprovince>MT</address1_stateorprovince>' .
                '<firstname>123</firstname>' .
                '<lastname>345 - ' . mktime() . '</lastname>' .
            '</entity>' .
            '</Create>' .
            '</soap:Body>';

        //prepare the SOAP message.
        $xml = '<?xml version="1.0" encoding="utf-8"?>' .
            '<soap:Envelope' .
                ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"' .
                ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' .
                ' xmlns:xsd="http://www.w3.org/2001/XMLSchema">' .
            $soapHeader .
            $soapBody .
            '</soap:Envelope>';

        //prepare header
        $headers = array(
            'SOAPAction' => 'http://schemas.microsoft.com/crm/2007/WebServices/Create',
            'Content-Type' => 'text/xml; charset="utf-8""',
            'Content-Length' => strlen($xml)
            );

        //SOAP call
        $result = $client->call('Create',
            $xml,
            'http://schemas.microsoft.com/crm/2007/WebServices',
            'http://schemas.microsoft.com/crm/2007/WebServices/Create',
            $headers);

        //result
        if ($client->fault) { //check for fault
            echo '<p><b>Fault: ';
            print_r($result);
            echo '</b></p>';
        }
       
        else { //no fault
            $err = $client->getError();
            if ($err) { // error
                echo 'Error: ' . $err . '';
                echo "\n\n# # # # # # # Request # # # # # # #\n";
                var_dump($client->request);
                echo "\n\n# # # # # # Response # # # # # # #\n";
                var_dump($client->response);
            }
            else { // display the result
            print_r($result);
            }
        }
    ?>

    vn
    2009년 9월 1일 화요일 오전 7:29
  • Is all this really required? 

    I though the point of using something like nusoap would be that it built all of the xml envelopes etc for you and all you have to pass to it is the method name and some parameters. ?? 

    I am trying to talk to ms crm 3 with php's soap class  but so far haven't got very far.  Does any one have any examples of this?  

    Is there somethin fundamentally different with the CRM web service that makes using it more complex than other webservices ??



    2009년 10월 21일 수요일 오후 9:49
  • Hello k2k9000,

    the nusoap-class is all you need. The speciality for the CRM webservice is the authentication-token. This might be because of the NTML-Authentication, but I am not sure.

    As mentioned at "Monday, August 10, 2009 9:06 AM" nusoap serializes the xml. With the suggested changes in the nusoap-class this works fine for me on CRM 4.0.

    In general you prepare the SOAP call like this (see Tuesday, September 01, 2009 7:29 AM):

    1) define some general configuration and variables
    2) create some strings (see above the strings for $soapHeader, $soapBody, $xml, $headers)
    3) do the SOAP Call (see $result=$client->call ....)
    4) operate the results (see //result)

    For getting more information how CRM expects the XML (=$soapBody), you can enable the tracing on the CRM-Webserver and do the action in browser diretcly. You can than have a look on the trace-log, how the CRM's XML should look like.

    vn
    2009년 10월 22일 목요일 오전 7:13
  • I too am having an authentication issue with this integration.  I am using pretty much the exact code posted by vneise on Tuesday, September 01, 2009 7:29 AM -
    I have a local copy of the WSDL and it seems to be parsing just fine - but my script errors out with this message

    2009-11-30 14:07:38.488139 nusoap_client: Error: HTTP Error: Unsupported HTTP response status 401 Unauthorized (soapclient->response has contents of the response)


    I am logging in using my online credentials and can access the WSDL in my browser

    this is my header that should be calling the authentication

    $soapHeader='<soap:Header>' .
            '<CrmAuthenticationToken xmlns="http://schemas.microsoft.com/crm/2007/WebServices">' .
                '<AuthenticationType xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">1</AuthenticationType>' .
                '<OrganizationName xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">'.$your_organization.'</OrganizationName>' .
                '<CallerId xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">00000000-0000-0000-0000-000000000000</CallerId>' .
            '</CrmAuthenticationToken>' .
            '</soap:Header>';

    any thoughts or pointing me in the right direction would be greatly appreciated.
    2009년 12월 1일 화요일 오후 5:22
  • Did you try to use AuthenticationType=0 (instead of 1 in your code)?

    > '<AuthenticationType xmlns="http://schemas.microsoft.com/crm/2007/CoreTypes">0</AuthenticationType>' .

    Kind regards,

    vn

    2009년 12월 2일 수요일 오전 8:05
  • Hi,

    Iam trying to connect CrmService using IFD auth type... Tried nearly every combination of things described on this forum, but still getting 

    HTTP/1.1 401 Unauthorized
    And yes, url is correct :(
    Can someone please provide piece of working code with IFD authentication ?
    Say for Fetch method with: <fetch mapping='logical'><entity name='account'><all-attributes/></entity></fetch> ?
    Thank you, iam stucked on this for days :(
    2010년 2월 10일 수요일 오전 1:34
  • Hi guys, I was having the exact same problem and managed to get it working; http://www.ifc0nfig.com/working-with-microsoft-dynamics-crm-4-0-soap-interface-with-php-and-nusoap/

    Regards, eth0.
    2010년 2월 23일 화요일 오후 9:19
  • This is great thread to follow if you are struggling with CRM communication using SOAP.

    Zenithy's post actually results in this great example for IFD authentication using native CURL with PHP - http://ow.ly/2GIz4 

    eth0izzle's post - http://ow.ly/2GIA4 also helped lots, and I would recommend using NuSoap for AD authentication with the CRM as native CURL for one reason or another couldn't achieve IFD authentication.

     

    Good luck.

    2010년 9월 20일 월요일 오전 9:27