obatfr/sfrest

A simple yet powerfull Salesforce REST API wrapper library.

1.0.1 2020-01-23 11:53 UTC

This package is not auto-updated.

Last update: 2020-08-21 13:06:28 UTC


README

Build Status Scrutinizer Code Quality

A simple yet powerfull tiny library to interact with Salesforce REST API.

It contain all you need to perform any REST call to Salesforce, including get/create/update/delete records, and performing SOQL queries with parameters.

It handle Login/Password and JWT (oAuth 2.0) authentication.

You can perform single request, or make multiple request in one call with the composite API (available since Summer '15).

This library is now open-source, any contribution is greatly appreciated.

Getting started

Setting up a Connected App

  1. Log into to your Salesforce org
  2. Click on Setup in the upper right-hand menu
  3. Under Build click Create > Apps
  4. Scroll to the bottom and click New under Connected Apps.
  5. Enter the following details for the remote application:
    • Connected App Name
    • API Name
    • Contact Email
    • Enable OAuth Settings under the API dropdown
    • Callback URL
    • Select access scope (If you need a refresh token, specify it here)
  6. Click Save

Installation

The installation can be done using Composer :

composer require mograine/sfrest:~1.0

Configuration

You should configure your config.json file. The structure can be found in SfRest/Config/config.json.dist

You can put this file in any directory, and set the filepath in SfRequest constructor. By default, the SfConfig will check if the file exist in SfRest/Config

{
    "method":               "JWT",                          # JWT or LOGINPASS
    "client_id":            "",                             # Can be found in "Connected Application" in Salesforce
    "client_secret":        "",                             # Can be found in "Connected Application" in Salesforce
    "login_uri":            "https://login.salesforce.com", # Login or Test
    "username":             "p.nom@mycompany.com",          # Your username
    "password":             "",                             # If method is LOGINPASS, your password. Else, left empty
    "rsa_key_full_path":    "~/.ssh/key.pem"                # Path to your private key
}
$sfRequest = new \SfRest\SfRequest("/root/config_sfrest.json");

Performing an action

Once you have configure the config.json file and instantiate a new SfRequest class, you are ready to go !

Here is some examples of what you can do :

$sfRequest = new \SfRest\SfRequest();

$results = $sfRequest->query('SELECT Name, Email FROM Lead Limit 10');

$postalCode = "12345";
$results = $sfRequest->query('SELECT Id, Name FROM Lead WHERE BillingPostalCode = ? Limit 10', $postalCode);

$account = new \StdClass();
$account->Name = "My super customer";
$sfRequest->createRecord("Lead", $account);

$sfRequest->prepare();
$sfRequest->createRecord("Lead", ["Name" => "My first super customer"]);
$sfRequest->updateRecord("Lead", 'a0E1800000kketp', ["Name" => "My second super customer"]);
$sfRequest->createRecord("Lead", ["Name" => "My third super customer"]);
$sfRequest->commit(); // Send all previous action in one API call

Availables Actions

Performing a SOQL Query

Simple Query

You can perform a SOQL Query with or without parameters.

By default, the parameters will be enclosed in quotes ('). If you need to avoid this (for example, if one of your parameter is a number), you can set the parameter type as SfRequest::PARAM_INT.

Types of parameters :

  • SfRequest::PARAM_STR : Default, enclosed in quotes
  • SfRequest::PARAM_INT : For numbers, parameter will not be enclosed
  • SfRequest::PARAM_NULL : Only value accepted is 'NULL'

$results = $sfRequest->query('SELECT Name, Email FROM Lead Limit 10');

$postalCode = "12345";
$results = $sfRequest->query('SELECT Id, Name FROM Lead WHERE BillingPostalCode = ?', $postalCode);

$postalCode = [12345, 54321];
$results = $sfRequest->query('SELECT Id, Name FROM Lead WHERE BillingPostalCode IN (?)', [SfRequest::PARAM_STR, $postalCode]);

$minimumEmployees = 10;
$maximumEmployees = 20;
$results = $sfRequest->query('SELECT Id, Name FROM Lead WHERE NumberOfEmployees >= ? AND NumberOfEmployees <= ?',
                             [SfRequest::PARAM_INT, $minimumEmployees],
                             [SfRequest::PARAM_INT, $maximumEmployees]);

"Big Data" Query

Sometime you need to get a lot of data from a single query (2000+). Salesforce will not send you back all the data in one API call, you will need to follow the "nextRecordsUrl" recursively.

Fortunately, SfRest can do it for you ! The "queryMore" method will follow the "nextRecordsUrl", and you will receive all data in a single array.


$results = $sfRequest->queryMore('SELECT Name, Email FROM Lead');

echo $results[0]->Name;

Get a record

If you know the id and type of a record you can fetch a set of fields from it.

$data = $sfRequest->getRecord('Lead', '00WL0000008wVl1MDE', ['name', 'email', 'phone']);

Create a Record

To create a record you only need the type and the fields values.

$sfRequest->createRecord("Lead", ['Name' => 'New Account']);

Updating a record

To update a record, you need the type and id of the record.

$sfRequest->updateRecord('Lead', '00WL0000008wVl1MDE', ['lastName' => 'Steve Jobs']);

Deleting records

Records can be deleted based on their id and type.

$sfRequest->deleteRecord('Lead', '00WL0000008wVl1MDE');

Performing multiple requests at once

Sometime you need to perform multiple actions at once. For example when your script generate many object, it is interresting to create them in only one API call.

This can be achieved by using 'batch mode', that will call the composite API (available since Summer '15).

You first need to call the 'prepare' method. All your next requests will be stored in cache and will wait for you to call the 'commit' method, sendind all previous requests at once.

If success, the commit function will return all query responses in the 'results' array, in the same order that you prepared them.

$sfRequest->prepare();

$sfRequest->createRecord("Lead", ['Name' => 'New Account 1']);
$sfRequest->createRecord("Lead", ['Name' => 'New Account 2']);
$sfRequest->query('SELECT Name, Email FROM Lead Limit 10');
$sfRequest->createRecord("Lead", ['Name' => 'New Account 3']);
$sfRequest->deleteRecord('Lead', '00WL0000008wVl1MDE');

$response = $sfRequest->commit();

$queryResponse = $response->results[2];

Errors

If something goes wrong the library will throw an exception.

All errors will be thrown using \SfRest\Exception\SfException

try
{
    $results = $sfClient->search('SELECT Name, Email FROM Lead Limit 10');
    print_r($results);
}
catch (\SfRest\Exception\SfException $e)
{
    echo $e->getMessage();
}

Credits

This wrapper was created by and for DMVP Formation company.

This README.md is largely inspired omniphx/forrest (connected app settings) and from crunch-accounting salesforce PHP wrapper.