3

I want to add contacts in my salesforce account via REST api, I already found some code to access the REST API but i dont know how I will integrate it to my account since when i tried the sample codes no new users where added to my contact list.

this is the link for the code i used:

http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php

the code i use:

<?php

            require_once ('soapclient/SforcePartnerClient.php');
            require_once ('soapclient/SforceEnterpriseClient.php');

            define("USERNAME", "xxxxxx@xxxx.xxx");
            define("PASSWORD", "xxxxxxxxxxxx");
            define("SECURITY_TOKEN", "gHN6m4YCrrf09jlIh2r65ndN");
            echo "------------------";
            try {
                echo "<table border=\"1\"><tr><td>";
                echo "First with the enterprise client<br/><br/>\n";

                $mySforceConnection = new SforceEnterpriseClient();
                $mySforceConnection->createConnection("soapclient/enterprise.wsdl.xml");

                if (isset($_SESSION['enterpriseSessionId'])) {
                    $location = $_SESSION['enterpriseLocation'];
                    $sessionId = $_SESSION['enterpriseSessionId'];

                    $mySforceConnection->setEndpoint($location);
                    $mySforceConnection->setSessionHeader($sessionId);

                    echo "Used session ID for enterprise<br/><br/>\n";
                } else {
                    $mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);

                    $_SESSION['enterpriseLocation'] = $mySforceConnection->getLocation();
                    $_SESSION['enterpriseSessionId'] = $mySforceConnection->getSessionId();

                    echo "Logged in with enterprise<br/><br/>\n";
                }

                $query = "SELECT Id, FirstName, LastName, Phone from Contact";
                $response = $mySforceConnection->query($query);

                echo "Results of query '$query'<br/><br/>\n";
                foreach ($response->records as $record) {
                    echo $record->Id.": ".$record->FirstName." "
                   .$record->LastName." ".$record->Phone."<br/>\n";
                }

                echo "<br/>Now, create some records<br/><br/>\n";

                $records = array();

                $records[0] = new stdclass();
                $records[0]->FirstName = 'John';
                $records[0]->LastName = 'Smith';
                $records[0]->Phone = '(510) 555-5555';
                $records[0]->BirthDate = '1957-01-25';

                $records[1] = new stdclass();
                $records[1]->FirstName = 'Mary';
                $records[1]->LastName = 'Jones';
                $records[1]->Phone = '(510) 486-9969';
                $records[1]->BirthDate = '1977-01-25';

                $response = $mySforceConnection->create($records, 'Contact');

               $ids = array();
                foreach ($response as $i => $result) {
                    echo $records[$i]->FirstName . " " . $records[$i]->LastName . " "
                            . $records[$i]->Phone . " created with id " . $result->id
                            . "<br/>\n";
                    array_push($ids, $result->id);
                }

                echo "<br/>Retrieve the newly created records:<br/><br/>\n";
                $response = $mySforceConnection->retrieve('Id, FirstName, LastName, Phone',
                                'Contact', $ids);
                foreach ($response as $record) {
                    echo $record->Id.": ".$record->FirstName." "
                   .$record->LastName." ".$record->Phone."<br/>\n";
                }

                echo "<br/>Next, update the new records<br/><br/>\n";

                $records[0] = new stdclass();
                $records[0]->Id = $ids[0];
                $records[0]->Phone = '(415) 555-5555';

                $records[1] = new stdclass();
                $records[1]->Id = $ids[1];
                $records[1]->Phone = '(415) 486-9969';

                $response = $mySforceConnection->update($records, 'Contact');
                foreach ($response as $result) {
                    echo $result->id . " updated<br/>\n";
                }

                echo "<br/>Retrieve the updated records to check the update:<br/><br/>\n";
                $response = $mySforceConnection->retrieve('Id, FirstName, LastName, Phone',
                                'Contact', $ids);
                foreach ($response as $record) {
                    echo $record->Id.": ".$record->FirstName." "
                   .$record->LastName." ".$record->Phone."<br/>\n";
                }

                echo "<br/>Let's remove those phone numbers<br/><br/>\n";

                $records[0] = new stdclass();
                $records[0]->Id = $ids[0];
                $records[0]->fieldsToNull = 'Phone';

                $records[1] = new stdclass();
                $records[1]->Id = $ids[1];
                $records[1]->fieldsToNull = 'Phone';

                $response = $mySforceConnection->update($records, 'Contact');
                foreach ($response as $result) {
                    echo $result->id . " updated<br/>\n";
                }

                echo "<br/>Retrieve the updated records again to check the update:";
                echo "<br/><br/>\n";
                $response = $mySforceConnection->retrieve('Id, FirstName, LastName, Phone','Contact', $ids);
                foreach ($response as $record) {
                    echo $record->Id.": ".$record->FirstName." "
                   .$record->LastName." ".$record->Phone."<br/>\n";
                }

          /*
                echo "<br/>Finally, delete the records:<br/><br/>\n";
                $response = $mySforceConnection->delete($ids);
                foreach ($response as $result) {
                           echo $result->id." deleted<br/>\n";
                }
          */
                echo "</td><td>";
                echo "Now let's use the partner client<br/><br/>\n";

                $mySforceConnection = new SforcePartnerClient();
                $mySforceConnection->createConnection("soapclient/partner.wsdl.xml");

                if (isset($_SESSION['partnerSessionId'])) {
                    $location = $_SESSION['partnerLocation'];
                    $sessionId = $_SESSION['partnerSessionId'];

                    $mySforceConnection->setEndpoint($location);
                    $mySforceConnection->setSessionHeader($sessionId);

                    echo "Used session ID for partner<br/><br/>\n";
                } else {
                    $mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);

                    $_SESSION['partnerLocation'] = $mySforceConnection->getLocation();
                    $_SESSION['partnerSessionId'] = $mySforceConnection->getSessionId();

                    echo "Logged in with partner<br/><br/>\n";
                }

                $query = "SELECT Id, FirstName, LastName, Phone from Contact";
                $response = $mySforceConnection->query($query);
                echo '<pre>';
                print_r($response);
                echo '</pre>';
                echo "Results of query '$query'<br/><br/>\n";
                foreach ($response->records as $record) {

                    echo $record->Id.": ".$record->fields->FirstName." "
                            .$record->fields->LastName." "
                            .$record->fields->Phone."\n";
                }

                echo "<br/>Now, create some records<br/><br/>\n";

                $records = array();

                $records[0] = new SObject();
                $records[0]->fields = array(
                    'FirstName' => 'John',
                    'LastName' => 'Smith',
                    'Phone' => '(510) 555-5555',
                    'BirthDate' => '1957-01-25'
                );
                $records[0]->type = 'Contact';

                $records[1] = new SObject();
                $records[1]->fields = array(
                    'FirstName' => 'Mary',
                    'LastName' => 'Jones',
                    'Phone' => '(510) 486-9969',
                    'BirthDate' => '1977-01-25'
                );
                $records[1]->type = 'Contact';

                $response = $mySforceConnection->create($records);

                $ids = array();
                foreach ($response as $i => $result) {
                           echo $records[$i]->fields["FirstName"]." "
                                .$records[$i]->fields["LastName"]." "
                                .$records[$i]->fields["Phone"]
                                ." created with id ".$result->id."<br/>\n";
                    array_push($ids, $result->id);
                }

                echo "<br/>Retrieve the newly created records:<br/><br/>\n";
                $response = $mySforceConnection->retrieve('Id, FirstName, LastName, Phone',
                                'Contact', $ids);
                foreach ($response as $record) {
                    echo $record->Id.": ".$record->fields->FirstName." "
                            .$record->fields->LastName." "
                            .$record->fields->Phone."<br/>\n";
                }

                echo "<br/>Next, update the new records<br/><br/>\n";

                $records[0] = new SObject();
                $records[0]->Id = $ids[0];
                $records[0]->fields = array(
                    'Phone' => '(415) 555-5555',
                );
                $records[0]->type = 'Contact';

                $records[1] = new SObject();
                $records[1]->Id = $ids[0];
                $records[1]->fields = array(
                    'Phone' => '(415) 486-9969',
                );
                $records[1]->type = 'Contact';

                $response = $mySforceConnection->update($records);
                foreach ($response as $result) {
                           echo $result->id." updated<br/>\n";
                }

                echo "<br/>Retrieve the updated records to check the update:<br/><br/>\n";
                $response = $mySforceConnection->retrieve('Id, FirstName, LastName, Phone',
                                'Contact', $ids);
                foreach ($response as $record) {
                    echo $record->Id.": ".$record->fields->FirstName." "
                   .$record->fields->LastName." ".$record->fields->Phone."<br/>\n";
                }

                echo "<br/>Let's remove those phone numbers<br/><br/>\n";

                $records[0] = new SObject();
                $records[0]->Id = $ids[0];
                $records[0]->fieldsToNull = 'Phone';
                $records[0]->type = 'Contact';

                $records[1] = new SObject();
                $records[1]->Id = $ids[1];
                $records[1]->fieldsToNull = 'Phone';
                $records[1]->type = 'Contact';

                $response = $mySforceConnection->update($records);
                foreach ($response as $result) {
                           echo $result->id." updated<br/>\n";
                }

                echo "<br/>Retrieve the updated records again to check the update:";
                echo "<br/><br/>\n";
                $response = $mySforceConnection->retrieve('Id, FirstName, LastName, Phone',
                                'Contact', $ids);
                foreach ($response as $record) {
                    echo $record->Id.": ".$record->fields->FirstName." "
                   .$record->fields->LastName." ".$record->fields->Phone."<br/>\n";
                }

      /*          echo "<br/>Finally, delete the records:<br/><br/>\n";
                $response = $mySforceConnection->delete($ids);
                foreach ($response as $result) {
                           echo $result->id." deleted<br/>\n";
                }
       */

                echo "</td></tr></table>";
            } catch (Exception $e) {
                echo "Exception ".$e->faultstring."<br/><br/>\n";
                echo "Last Request:<br/><br/>\n";
                echo $mySforceConnection->getLastRequestHeaders();
                echo "<br/><br/>\n";
                echo $mySforceConnection->getLastRequest();
                echo "<br/><br/>\n";
                echo "Last Response:<br/><br/>\n";
                echo $mySforceConnection->getLastResponseHeaders();
                echo "<br/><br/>\n";
                echo $mySforceConnection->getLastResponse();
            }
           ?>

I commented what i believe to be the deleting function part. still i dont see any of those contacts in my list or what do i have to do to see those contacts or where are they being added?

Any help will appreciated, I am just new to salesforce and want to integrate it to our system

thank you

  • 2
    Can you post your code, looking at the tutorial it is hard to say where you are struck – Rao Nov 15 '13 at 23:16
  • 1
    What was the output from the PHP script? Note that the PHP creates and then deletes an account - you won't see it afterwards. Also, ensure your user has permissions to create a user. Post code, post errors. – metadaddy Nov 16 '13 at 1:06
  • @rao updated my post and sorry for the late post. – magicianiam Nov 16 '13 at 14:26
  • @metadaddy my user is the system admin does that give it the necessary permissions? also the script outputs as expected though i don't know where to see the newly added records as they are not found at the manage contacts. – magicianiam Nov 16 '13 at 14:30
  • @magicianIam Yes - system admin should have the necessary perms. Copy the 18 character id in the output (after 'New record id '), and make a URL from your Salesforce host and that id - e.g. na9.salesforce.com/0015000000WywDHAAZ - in the browser, that URL should take you to the newly created user. – metadaddy Nov 16 '13 at 17:19
4
+50

A few things that I noticed:

  1. You posted your password and security token; I really hope those are dummy values.
  2. The script is creating Contacts without assigning them to Accounts, which means they're orphaned. Orphaned Contacts can be harder to find; in production, you generally always want your Contacts tied to Accounts.
  3. The script provides output with the ids of the new records. You can navigate directly to these records by putting the id in the URL. Ids of Contacts will always being with 003.

Example:

I created the Contact John Smith, with id 003P000000fJqfv. I can then navigate to https://[instance].salesforce.com/003P000000fJqfv to view John's record.

Your script provides this information (it's $record->Id):

echo "Results of query '$query'<br/><br/>\n";
                foreach ($response->records as $record) {
                    echo $record->Id.": ".$record->FirstName." "
                   .$record->LastName." ".$record->Phone."<br/>\n";
                }
  • why are instance different? mine is api and metadaddy is na9, are they settable somewhere? thank for pointing out about my password and token, though this is just a dummy account. also how do i assign them to an account and what thus an account here mean? thank you for the reply – magicianiam Nov 18 '13 at 15:19
  • 2
    Instances are not configurable; Salesforce assigns them. I recommend you start at developer.force.com/gettingstarteddevelopers and read the books and guides (especially those related to the Sales Cloud) so that you have a good idea of how the system is designed to work. These docs will answer a lot of questions that are too broad for this site. – Mike Chale Nov 18 '13 at 15:27
  • thank you for that link, though would you have any idea as to why when i run the same script above I get this error now: Exception API_DISABLED_FOR_ORG: API is not enabled for this Organization or Partner i still have 27 days in my trial account though. any ideas. will read the docs for now. thank you – magicianiam Nov 18 '13 at 15:30
  • Trial orgs should have the API enabled, though at reduced limits. Enabling API access is a different question, though. – Mike Chale Nov 18 '13 at 15:35
  • 1
    Just searching 'salesforce reset security token' should lead you to the official documentation. – Mike Chale Nov 18 '13 at 15:51
1

if you want to insert using records Through cURL the Go through this First Create a Connected app in salesforce ,,Navigation : Setup -->Create-->App-->RemoteApp--> New-->Fill the Required Details & Check on Api OAuth Enable ..enter Callback URL as https://ap1.salesforce.com/services/oauth2/token(Note my sever is ap1 ).then after saving you'll obtain customer id and customer secret key ..then install cURL .these are the links for installing cURL http://guides.instructure.com/s/2204/m/4214/l/83393-how-do-i-install-and-use-curl-on-a-windows-machine .then check whether cURL is Installed sucessfully or not by type these command .i.e curl www.google.com.or curl --help .

use these command for obtaining OAuth From Salesforce Using cURL .i,e curl --form client_id=[Your client Id] --form client_secret=[Your client secret] --form grant_type=password --form username=[Your Username] --form password=[Your Password+Your Security Token] -k https://[Your salesforce instance].salesforce.com/services/oauth2/token

eg: curl --form client_id=3MVG9Y6d_Btp4xp4It6xCeiiph72wrU43OJxnkAmHpX62r5ZknjtDZhKUBqyEsOKLzE_AW.Z6xR6yE8Y9MbYt --form client_secret=5993237303335770812 --form grant_type=password --form username=xxxy@force.com --form password=xxxxCaCeHxYxEKIzW721Vq7ljWce -k https://ap1.salesforce.com/services/oauth2/token

after executing these command you'll get a session id ..copy that session_id .

use that seesion of for inserting records ..by using these command .i,e
curl -H "Authorization:OAuth use your session_id" -H "Content-Type: application/json" -d @Test.json "https://ap1.salesforce.com/services/data/v20.0/sobjects/Account/" after executing these command you'll get a successful message with record id .

Note :@test.json is json file saved in my desktop .my test.json file contains data like this

{ "name": "testValue1" }

0

Sorry guys, but I am not good at PHP, So here I am providing a solution in jQuery.

Hope it helps :

 $.ajax({
        async : true,
        method:'post',
        url : 'https://ap1.salesforce.com/services/data/v24.0/sobjects/Contact',
        data : '{"LastName": "Express Logistics and Transport"}',
        headers : {
            'Content-Type' : 'application/json; charset=UTF-8',
            'Authorization' : 'OAuth ' + YourOAuthToken,

        },
        success : function(response) {
            //TO DO on Success
        },
        failure : function(response) {
            TO DO on Failure
        }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.