Integrating PHP with Salesforce via REST and SOAP API

Integrating with Salesforce CRM begins with the Force.com Web Services API. The API is SOAP or REST 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;

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.
  2. 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

  

config.php

 

oauth.php

 

oauth_callback.php

 

demo_rest.php


"; foreach ((array) $response['records'] as $record) { echo $record['Id'] . ", " . $record['Name'] . "
"; } echo "
"; } 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

"; curl_close($curl); $response = json_decode($json_response, true); $id = $response["id"]; echo "New record id $id

"; 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

"; curl_close($curl); $response = json_decode($json_response, true); foreach ((array) $response as $key => $value) { echo "$key:$value
"; } echo "
"; } 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

"; 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

"; curl_close($curl); } ?>

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:

  • http://developer.force.com/cookbook/recipe/interact-with-the-forcecom-rest-api-from-php
  • https://help.salesforce.com/apex/HTViewHelpDoc?id=connected_app_create.htm
  • https://resources.docs.salesforce.com/sfdc/pdf/api_rest.pdf

About MST

At MST Solutions our cornerstone is to adapt, engage and create solutions which guarantee the success of our clients. The talent of our team and experiences in varied business verticals gives us an advantage over other competitors.

Recent Articles

Work with us.

Our people aren’t just employees, they are key to the success of our business. We recognize the strengths of each individual and allow them time and resources to further develop those skills, crafting a culture of leaders who are passionate about where they are going within our organization.