You are using an older browser that might negatively affect how this site is displayed. Please update to a modern browser to have a better experience. Sorry for the inconvenience!

Integrating PHP with Salesforce via REST and SOAP API


Salesforce Integration with Php begins with the Force.com Web Services API. The API is Salesforce SOAP API or Salesforce REST API based; so, you can use PHP’s built in SOAP extension to make calls to the service, but in this tutorial I’ll be using the PHP Toolkit provided by Salesforce; you still need to have the PHP Soap extension installed, but the toolkit provides convenient utility methods for all of the available api calls.

The Force.com REST API provides you with a powerful, convenient, and simple Web services interface for interacting with Force.com. Its advantages include ease of integration and development, and it is an excellent choice of technology for use with mobile applications and Web 2.0 projects. The REST API is accessible from any programming languages, such as PHP, Ruby, .NET, or any other environment.

Integrating PHP with Salesforce using REST API Architecture

This diagram shows the authentication process of connection establishment between PHP and Salesforce.

  1. The application redirects the user to the appropriate Salesforce authorization endpoint, such as https://login.salesforce.com/services/oauth2/authorize. The following parameters are required.

C:\Users\MST1\Desktop\1.jpg

An example authorization URL might look something like the following:

https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCscA9GE&redirect_uri=https%3A%2F%2Fwww.mysite.com%2Fcode_callback.jsp&state=mystate

  1. The user logs into Salesforce with their credentials. The user is interacting with the authorization endpoint directly, so the application never sees the user’s credentials. After successfully logging in, the user is asked to authorize the application. Note that if the user has already authorized the application, this step is skipped.

  1. Once Salesforce confirms that the client application is authorized, the end-user’s Web browser is redirected to the callback URL specified by the redirect_uri parameter. Salesforce appends authorization information to the redirect URL with the following values

C:\Users\MST1\Desktop\2.jpg

An example callback URL with authorization information might look something like:

https://www.mysite.com/authcode_callback?code=aWekysIEeqM9PiThEfm0Cnr6MoLIfwWyRJcqOqHdF8f9INokharAS09ia7UNP6RiVScerfhc4w%3D%3D

  1. The application extracts the authorization code and passes it in a request to Salesforce for an access token. This request is a POST request sent to the appropriate Salesforce token request endpoint, such as https://login.salesforce.com/services/oauth2/token. The following parameters are required:

C:\Users\MST1\Desktop\4.jpg

An example access token POST request might look something like:

POST/services/oauth2/tokenHTTP/1.1Host:login.salesforce.comgrant_type=authorization_code&code=aPrxsmIEeqM9PiQroGEWx1UiMQd95_5JUZVEhsOFhS8EVvbfYBBJli2W5fn3zbo.8hojaNW_1g%3D%3D&client_id=3MVG9lKcPoNINVBIPJjdw1J9LLM82HnFVVX19KY1uA5mu0QqEWhqKpoW3svG3XHrXDiCQjK1mdgAvhCs

cA9GE&client_secret=1955279925675241571&redirect_uri=https%3A%2F%2Fwww.mysite.com%2Fcode_callback.jsp.

  1. If this request is successful, the server returns a response body that contains the following:

  1. The application uses the provided access token and refresh token to access protected user data

Steps to connect PHP with Salesforce

    Step 1

        We have to create the Remote Access or Connected App in Salesforce.

    Step 2

        Develop the PHP project and configure the REST API.

Connected App in Salesfoce

Create the Connected App in Salesforce and get the consumer key and consumer secret key for REST API Oauth authentication.

Log in to Salesforce, navigate to Setup ➤ Create ➤Apps. Under the Connected App  section, click New to create a new Connected App.

(Note: 1. The CallbackUrl is https://localhost/resttest/oauth_callback.php in API Enable Oauth Settings. 2. Note down the Consumer Key and Consumer Secret Key (click to reveal))

Create the PHP Project

    Create a directory or folder named as resttest in your Web server document root (Eg; htdocs or www). Save the following five files in the resttest directory.

    The files are

  1. index.html

  2. config.php

  3. oauth.php

  4. oauth_callback.php

  5. demo_rest.php

Source Code for the above Files

index.html

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>REST/OAuth Example</title>

</head>

<body>

<script type="text/javascript" language="javascript">

   if (location.protocol != "https:") {

       document.write("OAuth will not work correctly from plain http. "+

                       "Please use an https URL.");

   } else {

       document.write("<a href=\"oauth.php\">Click here to retrieve accounts from Salesforce via REST/OAuth.</a>");

   }

</script>

</body>

</html>

config.php

<?php

define("CLIENT_ID", "PUT_YOUR_CONSUMER_KEY_HERE");

define("CLIENT_SECRET", "PUT_YOUR_CONSUMER_SECRET_HERE");

define("REDIRECT_URI", "https://localhost/resttest/oauth_callback.php");

define("LOGIN_URI", "https://login.salesforce.com");

?>

oauth.php

<?php

require_once 'config.php';

$auth_url = LOGIN_URI

       . "/services/oauth2/authorize?response_type=code&client_id="

       . CLIENT_ID . "&redirect_uri=" . urlencode(REDIRECT_URI);

header('Location: ' . $auth_url);

?>

oauth_callback.php

<?php

require_once 'config.php';

session_start();

$token_url = LOGIN_URI . "/services/oauth2/token";

$code = $_GET['code'];

if (!isset($code) || $code == "") {

   die("Error - code parameter missing from request!");

}

$params = "code=" . $code

   . "&grant_type=authorization_code"

   . "&client_id=" . CLIENT_ID

   . "&client_secret=" . CLIENT_SECRET

   . "&redirect_uri=" . urlencode(REDIRECT_URI);

$curl = curl_init($token_url);

curl_setopt($curl, CURLOPT_HEADER, false);

curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

curl_setopt($curl, CURLOPT_POST, true);

curl_setopt($curl, CURLOPT_POSTFIELDS, $params);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 200 ) {

   die("Error: call to token URL $token_url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));

}

curl_close($curl);

$response = json_decode($json_response, true);

$access_token = $response['access_token'];

$instance_url = $response['instance_url'];

if (!isset($access_token) || $access_token == "") {

   die("Error - access token missing from response!");

}

if (!isset($instance_url) || $instance_url == "") {

   die("Error - instance URL missing from response!");

}

$_SESSION['access_token'] = $access_token;

$_SESSION['instance_url'] = $instance_url;

header( 'Location: demo_rest.php' ) ;

?>

demo_rest.php

<?php

session_start();

function show_accounts($instance_url, $access_token) {

   $query = "SELECT Name, Id from Account LIMIT 100";

   $url = "$instance_url/services/data/v20.0/query?q=" . urlencode($query);

   $curl = curl_init($url);

   curl_setopt($curl, CURLOPT_HEADER, false);

   curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

   curl_setopt($curl, CURLOPT_HTTPHEADER,

           array("Authorization: OAuth $access_token"));

   $json_response = curl_exec($curl);

   curl_close($curl);

   $response = json_decode($json_response, true);

   $total_size = $response['totalSize'];

   echo "$total_size record(s) returned<br/><br/>";

   foreach ((array) $response['records'] as $record) {

       echo $record['Id'] . ", " . $record['Name'] . "<br/>";

   }

   echo "<br/>";

}

function create_account($name, $instance_url, $access_token) {

   $url = "$instance_url/services/data/v20.0/sobjects/Account/";



   $content = json_encode(array("Name" => $name));

   $curl = curl_init($url);

   curl_setopt($curl, CURLOPT_HEADER, false);

   curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

   curl_setopt($curl, CURLOPT_HTTPHEADER,

           array("Authorization: OAuth $access_token",

               "Content-type: application/json"));

   curl_setopt($curl, CURLOPT_POST, true);

   curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

   $json_response = curl_exec($curl);

   $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

   if ( $status != 201 ) {

       die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));

   }

       echo "HTTP status $status creating account<br/><br/>";

   curl_close($curl);

   $response = json_decode($json_response, true);

   $id = $response["id"];

   echo "New record id $id<br/><br/>";

   return $id;

}

function show_account($id, $instance_url, $access_token) {

   $url = "$instance_url/services/data/v20.0/sobjects/Account/$id";



   $curl = curl_init($url);

   curl_setopt($curl, CURLOPT_HEADER, false);

   curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

   curl_setopt($curl, CURLOPT_HTTPHEADER,

           array("Authorization: OAuth $access_token"));

   $json_response = curl_exec($curl);

   $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

   if ( $status != 200 ) {

       die("Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));

   }

   echo "HTTP status $status reading account<br/><br/>";

   curl_close($curl);

   $response = json_decode($json_response, true);

   foreach ((array) $response as $key => $value) {

       echo "$key:$value<br/>";

   }

   echo "<br/>";

}



function update_account($id, $new_name, $city, $instance_url, $access_token) {

   $url = "$instance_url/services/data/v20.0/sobjects/Account/$id";

   $content = json_encode(array("Name" => $new_name, "BillingCity" => $city));

   $curl = curl_init($url);

   curl_setopt($curl, CURLOPT_HEADER, false);

   curl_setopt($curl, CURLOPT_HTTPHEADER,

           array("Authorization: OAuth $access_token",

               "Content-type: application/json"));

   curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH");

   curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

   curl_exec($curl);

   $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

   if ( $status != 204 ) {

       die("Error: call to URL $url failed with status $status, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));

   }

   echo "HTTP status $status updating account<br/><br/>";

   curl_close($curl);

}

function delete_account($id, $instance_url, $access_token) {

   $url = "$instance_url/services/data/v20.0/sobjects/Account/$id";

   $curl = curl_init($url);

   curl_setopt($curl, CURLOPT_HEADER, false);

   curl_setopt($curl, CURLOPT_HTTPHEADER,

           array("Authorization: OAuth $access_token"));

   curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE");

   curl_exec($curl);

   $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

   if ( $status != 204 ) {

       die("Error: call to URL $url failed with status $status, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl));

   }

   echo "HTTP status $status deleting account<br/><br/>";

   curl_close($curl);

}

?>

<html>

   <head>

   </head>

   <body>

       <tt>

           <?php

           $access_token = $_SESSION['access_token'];

           $instance_url = $_SESSION['instance_url'];

           if (!isset($access_token) || $access_token == "") {

               die("Error - access token missing from session!");

           }

           if (!isset($instance_url) || $instance_url == "") {

               die("Error - instance URL missing from session!");

           }

           show_accounts($instance_url, $access_token);

           $id = create_account("My New Org", $instance_url, $access_token);

           show_account($id, $instance_url, $access_token);

           show_accounts($instance_url, $access_token);

           update_account($id, "My New Org, Inc", "San Francisco",

                   $instance_url, $access_token);

           show_account($id, $instance_url, $access_token);

           show_accounts($instance_url, $access_token);

           delete_account($id, $instance_url, $access_token);

           show_accounts($instance_url, $access_token);

           ?>

       </tt>

   </body>

</html>

Restart your browser to clear out any session cookies, then browse to https://localhost/resttest/and click the link. Login as usual, and you will be presented with a screen requesting authorization for the sample app to access your data. Upon approving access, you will see the app’s output in the browser, similar to the following:

Output

12 record(s) returned

0015000000VALDtAAP, GenePoint

0015000000VALDuAAP, United Oil & Gas, UK

0015000000VALDvAAP, United Oil & Gas, Singapore

0015000000VALDwAAP, Edge Communications

0015000000VALDxAAP, Burlington Textiles Corp of America

0015000000VALDyAAP, Pyramid Construction Inc.

0015000000VALDzAAP, Dickenson plc

0015000000VALE0AAP, Grand Hotels & Resorts Ltd

0015000000VALE1AAP, Express Logistics and Transport

0015000000VALE2AAP, University of Arizona

0015000000VALE3AAP, United Oil & Gas Corp.

0015000000VALE4AAP, sForce

HTTP status 201 creating account

New record id 0015000000WywDHAAZ

HTTP status 200 reading account

attributes:Array

Id:0015000000WywDHAAZ

IsDeleted:

Integrating PHP with Salesforce using SOAP API

Requirements

PHP Toolkit (Download it from developerforce.com).

  • PHP 5.2 (PHP 5.3 required for API relationships)

  • SOAP Enabled

  • SSL Enabled

From Salesforce

  • Generate the WSDL

  • Get the Security Token

Generate your WSDL

The first step in accessing the Salesforce via the API is to generate a WSDL. The SOAP client requires the WSDL in order to know what calls it can make to the server.

Navigate to Set Up→Develop→API.  Now, click ‘Generate Enterprise WSDL’ link. Leave all the versions with the default values, and click the ‘Generate’ button. Finally, save the XML into your client application.

Screenshot of salesforce setup for generating a wsdl

Get your Security Token

 To call the SOAP service, you need to provide User Name, Password, and Salesforce Security Token; so, generate the Security Token from Salesforce.

Screenshot of salesforce setup for resetting login security token

The Architecture of SOAP API

This diagram shows how the authentication happens when the PHP client application connects with Salesforce using SOAP API

C:\Users\MST1\Desktop\sfdc-solution-copy.png

  • User logs into the remote site; login credentials are passed to custom PHP app.

  • PHP app makes login request to SFDC Web Services using the SOAP APISFDC Web Services using the SOAP API

  • SFDCSFDC Web Service sends response with session ID,  if user is successfully authenticated

  • The custom app redirects to a landing page and displays a “login success” message

  • Custom app seamlessly redirects user to an SFDC page (optional)SFDC page (optional)

The session IDs can be used to seamlessly redirect to pages on Salesforce.com without the need to log in again.

Steps to connect PHP with Salesforce using SOAP API

  1.     The first step to using the PHP Toolkit is to create a connection using either SforceEnterpriseClient or SforcePartnerClient

  2.     In both cases, you must ensure that your user has API access enabled (Setup|Manage Users|Users|Select your user|Click the user’s profile|Administrative Permissions).

  3.      Concatenate the password with the security token to form the second argument for the login method.

Connectivity coding for Enterprise (Available in PHP Tollkit)

define("USERNAME", "username@example.com");

define("PASSWORD", "example");

define("SECURITY_TOKEN", "example");

include('soapclient/SforceEnterpriseClient.php');

require_once("soapclient/SforceHeaderOptions.php");

$mySforceConnection = new SforceEnterpriseClient();

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

$mySforceConnection->login(USERNAME, PASSWORD.SECURITY_TOKEN);

Sample Query response from PHP to Salesforce

This is the sample code for querying the contact object data from PHP.

$query = "SELECT Id, FirstName, LastName from Contact";

$response = $mySforceConnection->query($query); // QueryResult object is only for PARTNER client $queryResult = new QueryResult($response);

foreach ($queryResult->records as $record)

{

echo "Id = ".$record->Id; 

echo "First Name = ".$record->FirstName; 

echo "Last Name = ".$record->LastName;

}

References: