ProgramMatek: Utilizing the Salesforce PHP SDK

Salesforce is renowned for its robust CRM services. As a customer relationship management platform, it offers a vast array of tools and features. Among its many powerful capabilities, Salesforce provides a comprehensive API that enables users to create, retrieve, update, and delete records. In this article, we will explore the basics of leveraging Salesforce’s REST API with PHP.

Authentication: Establishing Secure Access

Before we can proceed with any interactions, authentication is essential to obtain an access token. Salesforce offers several authentication options, including the Web Server flow, User-agent flow, and Username-password flow. For the purpose of this article, we will focus on the Username-password flow.

To request an access token, we need to follow a two-step process. First, let’s request the access token:

use GuzzleHttp{Client, RequestOptions};

$apiCredentials = [
    'client_id' => 'YOUR SALESFORCE CLIENT ID',
    'client_secret' => 'YOUR SALESFORCE CLIENT SECRET',
    'security_token' => 'YOUR SALESFORCE SECURITY TOKEN',
];

$userCredentials = [
    'username' => 'YOUR SALESFORCE USERNAME',
    'password' => 'YOUR SALESFORCE PASSWORD',
];

$client = new Client(['base_uri' => 'YOUR SALESFORCE URL']);

try {
    $response = $client->post('services/oauth2/token', [
        RequestOptions::FORM_PARAMS => [
            'grant_type' => 'password',
            'client_id' => $apiCredentials['client_id'],
            'client_secret' => $apiCredentials['client_secret'],
            'username' => $userCredentials['username'],
            'password' => $userCredentials['password'] . $apiCredentials['security_token'],
        ],
    ]);

    $data = json_decode($response->getBody());
} catch (Exception $exception) {
    throw new SalesforceException('Unable to connect to Salesforce');
}

It’s important to note that when requesting the access token, we must combine the user password with the security token. In case any issues arise during this request, a custom SalesforceException should be thrown for proper error handling.

See also  Introducing ProgramMatek Online Banking Solution

The access token will be returned as a property of the $data object. Before proceeding, it is crucial to validate the authenticity of the access token:

$hash = hash_hmac(
    'sha256',
    $data->id . $data->issued_at,
    $apiCredentials['client_secret'],
    true
);

if (base64_encode($hash) !== $data->signature) {
    throw new SalesforceException('Access token is invalid');
}

$accessToken = $data->access_token; // Valid access token

Assuming everything went smoothly, we now possess a valid access token. In a real application, it is advisable to cache this token for future use to prevent excessive authentication requests to Salesforce.

Describing Objects: Gathering Insights

With successful authentication and validated access token, we can begin extracting information from Salesforce. Let’s start by describing an object to determine the available fields for working with it:

try {
    $response = $client->request()->get('services/data/v45.0/sobjects/Account/describe', [
        RequestOptions::HEADERS => [
            'Authorization' => 'Bearer ' . $accessToken,
            'X-PrettyPrint' => 1,
        ],
    ]);
} catch (Exception $exception) {
    throw new SalesforceException('Unable to describe Account object');
}

$accountObject = json_decode($response->getBody());

Using the access token obtained earlier, we retrieve information about the Account object. For instance, $accountObject->fields provides us with a list of available fields for the Account object.

By modifying the URL in the Guzzle’s get() method, we can describe different objects. For example, to describe the User object instead of the Account object, we would change the URL from:

services/data/v45.0/sobjects/Account/describe

to:

services/data/v45.0/sobjects/User/describe

Creating an Account: Adding a New Record

Now that we understand how to describe an object, we can proceed to create a new record. Let’s focus on the Account object and make a POST request for this purpose:

$data = [
    'FirstName' => 'Grace',
    'LastName' => 'Hopper',
];

try {
    $response = $client->request()->post('services/data/v45.0/sobjects/Account/', [
        RequestOptions::HEADERS => [
            'Authorization' => 'Bearer ' . $accessToken,
            'X-PrettyPrint' => 1,
        ],
        RequestOptions::JSON => $data,
    ]);

    $newRecord = json_decode($response->getBody());
} catch (Exception $exception) {
    throw new SalesforceException('Unable to create Account record');
}

$accountId = $newRecord->id ?? null;

Assuming no validation errors occur with the fields used in the creation process, the request will return the case-sensitive ID of the newly created account. It is crucial to utilize this ID when retrieving, updating, or deleting a record.

See also  PHP vs IOP: Choosing the Right Addiction Treatment Program

Finding Accounts: Utilizing SOQL

Understanding how to query Salesforce’s REST API to search for records is immensely valuable. For this purpose, Salesforce provides SOQL (Salesforce Object Query Language), which closely resembles SQL. In the following example, we will search for the ‘Grace Hopper’ record and any other accounts with the same last name:

$query = "SELECT Id, FirstName, LastName FROM Account WHERE LastName = 'Hopper'";

try {
    $response = $client->request()->get('services/data/v45.0/query', [
        RequestOptions::HEADERS => [
            'Authorization' => 'Bearer ' . $accessToken,
            'X-PrettyPrint' => 1,
        ],
        RequestOptions::QUERY => [
            'q' => $query,
        ],
    ]);

    $accounts = json_decode($response->getBody());
} catch (Exception $exception) {
    throw new SalesforceException('Unable to query Salesforce Accounts');
}

$resultsFound = $accounts->totalSize;
$results = $accounts->records;

The response will contain the number of records found ($accounts->totalSize) and the records themselves ($accounts->records).

Getting an Account: Retrieving a Record

If we already have the case-sensitive ID of a record, it is effortless to retrieve the complete record without the need for a SOQL query:

try {
    $response = $client->request()->get('services/data/v45.0/sobjects/Account/' . $accountId, [
        RequestOptions::HEADERS => [
            'Authorization' => 'Bearer ' . $accessToken,
            'X-PrettyPrint' => 1,
        ],
    ]);
} catch (Exception $exception) {
    throw new SalesforceException('Unable to get Account record');
}

$account = json_decode($response->getBody());

Updating an Account: Modifying a Record

To update a record, we can utilize the case-sensitive ID:

$data = [
    'LastName' => 'Murray',
];

try {
    $response = $client->request()->patch('services/data/v45.0/sobjects/Account/' . $accountId, [
        RequestOptions::HEADERS => [
            'Authorization' => 'Bearer ' . $accessToken,
            'X-PrettyPrint' => 1,
        ],
        RequestOptions::JSON => $data,
    ]);
} catch (Exception $exception) {
    throw new SalesforceException('Unable to update Account record');
}

It’s worth noting that this is a patch request, with the record’s ID passed as part of the request URL.

Deleting an Account: Removing a Record

Lastly, if we wish to delete a record:

try {
    $response = $client->request()->delete('services/data/v45.0/sobjects/Account/' . $accountId, [
        RequestOptions::HEADERS => [
            'Authorization' => 'Bearer ' . $accessToken,
            'X-PrettyPrint' => 1,
        ],
    ]);
} catch (Exception $exception) {
    throw new SalesforceException('Unable to delete Account record');
}

This represents a delete request.

See also  Understanding Php Eating Disorder

Further Reading

We hope this introduction to utilizing Salesforce’s REST API has been helpful. While we have covered the fundamentals, we encourage you to explore the official documentation for more comprehensive information. The API offers straightforward methods for creating, retrieving, updating, and deleting records. Understanding SOQL provides additional versatility, and the Salesforce website provides a complete reference for it.

For more information about ProgramMatek and our services, please visit ProgramMatek.