PHPackages                             digitalmarketinginstitute/salesforce-api-php-wrapper - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [HTTP &amp; Networking](/categories/http)
4. /
5. digitalmarketinginstitute/salesforce-api-php-wrapper

ActiveLibrary[HTTP &amp; Networking](/categories/http)

digitalmarketinginstitute/salesforce-api-php-wrapper
====================================================

A library for interacting with the Salesforce REST API and managing the OAuth flow

1.1.5(1y ago)03.3kMITPHPPHP &gt;=8.0

Since Jun 11Pushed 1y agoCompare

[ Source](https://github.com/digitalmarketinginstitute/salesforce-api-php-wrapper)[ Packagist](https://packagist.org/packages/digitalmarketinginstitute/salesforce-api-php-wrapper)[ Docs](https://github.com/crunch-accounting/salesforce-api-php-wrapper)[ RSS](/packages/digitalmarketinginstitute-salesforce-api-php-wrapper/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (4)Versions (11)Used By (0)

**Please note that this repository has now been archived and is no longer supported**

[![Current Version](https://camo.githubusercontent.com/063ac082463fe456e673bcef6c386a427550b8ba8175ac59aa86db01d1491472/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6372756e63682d6163636f756e74696e672f73616c6573666f7263652d6170692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/crunch-accounting/salesforce-api)[![License](https://camo.githubusercontent.com/98d16df441e24327c4b09cb6adb805e71e7f1ab33b68c1d0358fd989400b44ea/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6372756e63682d6163636f756e74696e672f73616c6573666f7263652d6170692e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/crunch-accounting/salesforce-api)[![Scrutinizer](https://camo.githubusercontent.com/f8218c8edf50bea9368881f808e4827eb91060c91ed3a0df24a6eb38b1397d73/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f6372756e63682d6163636f756e74696e672f73616c6573666f7263652d6170692d7068702d777261707065722e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/crunch-accounting/salesforce-api-php-wrapper/)[![Travis](https://camo.githubusercontent.com/56013a02cec5eb87858950a478f7ff8cd2859b3b81d9436a6192fd9b3c06682d/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f6372756e63682d6163636f756e74696e672f73616c6573666f7263652d6170692d7068702d777261707065722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/crunch-accounting/salesforce-api-php-wrapper)

Salesforce PHP Library (Archived)
=================================

[](#salesforce-php-library-archived)

A simple library for interacting with the Salesforce REST API.

Methods for setting up a connection, requesting an access token, refreshing the access token, saving the access token, and making calls against the API.

Getting started
---------------

[](#getting-started)

**Installation:**The package should be installed through composer and locked to a major version

```
composer require crunch-accounting/salesforce-api:~1.0

```

**Creating an oauth token:**You need to fetch an access token for a user, all followup requests will be performed against this user.

```
$sfClient = \Crunch\Salesforce\Client::create('https://test.salesforce.com/', 'clientid', 'clientsecret');

if ( ! isset($_GET['code'])) {

    $url = $sfClient->getLoginUrl('http://example.com/sf-login');
    header('Location: '.$url);
    exit();

} else {

    $token = $sfClient->authorizeConfirm($_GET['code'], 'http://example.com/sf-login');
    $tokenGenerator = new \Crunch\Salesforce\AccessTokenGenerator();
    $accessToken = $tokenGenerator->createFromSalesforceResponse($token);

    $_SESSION['accessToken'] = $accessToken->toJson();

}
```

**Performing an action:**Once you have an access token you can perform requests against the API.

```
$sfClient = \Crunch\Salesforce\Client::create('https://test.salesforce.com/', 'clientid', 'clientsecret');
$tokenGenerator = new \Crunch\Salesforce\AccessTokenGenerator();
$accessToken = $tokenGenerator->createFromJson($_SESSION['accessToken']);
$sfClient->setAccessToken($accessToken);

$results = $sfClient->search('SELECT Name, Email FROM Lead Limit 10');
print_r($results);
```

The token will expire after an hour so you should make sure you're checking the expiry time and refreshing accordingly.

Setting up the Salesforce client
--------------------------------

[](#setting-up-the-salesforce-client)

The client can be configured in two ways, you can call the static create method above passing in the login url and oauth details or you can use a configuration object as in the example below. This is useful when you need to resolve the client out of an ioc container.

The configuration data for the client is passed in through a config file which must implement `\Crunch\Salesforce\ClientConfigInterface`

For example

```
class SalesforceConfig implements \Crunch\Salesforce\ClientConfigInterface {

    /**
     * @return string
     */
    public function getLoginUrl()
    {
        return 'https://test.salesforce.com/';
    }

    /**
     * @return string
     */
    public function getClientId()
    {
        return 'clientid';
    }

    /**
     * @return string
     */
    public function getClientSecret()
    {
        return 'clientsecret';
    }
}
```

A config class is provided and can be used if needed. `\Crunch\Salesforce\ClientConfig`

The Salesforce client can then be instantiated with the config object and an instance of the Guzzle v4 client.

```
$sfConfig = new SalesforceConfig();
$sfClient = new \Crunch\Salesforce\Client($sfConfig, new GuzzleHttp\Client());
```

Authentication
--------------

[](#authentication)

Authentication happens via oauth2 and the login url can be generated using the `getLoginUrl` method, you should pass this your return url for the send stage of the oauth process.

```
$url = $sfClient->getLoginUrl('http://exmaple.com/sf-login');
```

You should redirect the user to this returned url, on completion they will be redirected back with a code in the query string.

The second stage of the authentication can then be completed.

```
$token = $sfClient->authorizeConfirm($_GET['code'], 'http://exmaple.com/sf-login');
```

The token returned from here is the raw data and can be passed to the access token generator to make an `AccessToken`.

```
$tokenGenerator = new \Crunch\Salesforce\AccessTokenGenerator();
$accessToken = $tokenGenerator->createFromSalesforceResponse($token);
```

### Storing the access token

[](#storing-the-access-token)

This access token should be stored. A method to store this on the file system is provided but this isn't required.

The example above uses the php session to achieve the same result.

The `LocalFileStore` object needs to be instantiated with access to the token generator and a config class which implements `\Crunch\Salesforce\TokenStore\LocalFileConfigInterface`

```
class SFLocalFileStoreConfig implements \Crunch\Salesforce\TokenStore\LocalFileConfigInterface {

    /**
     * The path where the file will be stored, no trailing slash, must be writable
     *
     * @return string
     */
    public function getFilePath()
    {
        return __DIR__;
    }
}
```

The token store can then be created and used to save the access token to the local file system as well as fetching a previously saved token.

```
$tokenStore = new \Crunch\Salesforce\TokenStore\LocalFile(new \Crunch\Salesforce\AccessTokenGenerator, new SFLocalFileStoreConfig);

//Save a token
$tokenStore->saveAccessToken($accessToken);

//Fetch a token
$accessToken = $tokenStore->fetchAccessToken();
```

### Refreshing the token

[](#refreshing-the-token)

The access token only lasts 1 hour before expiring so you should regularly check its status and refresh it accordingly.

```
$accessToken = $tokenStore->fetchAccessToken();

if ($accessToken->needsRefresh()) {

	$accessToken = $sfClient->refreshToken();

    $tokenStore->saveAccessToken($accessToken);
}
```

Making requests
---------------

[](#making-requests)

Before making a request you should instantiate the client as above and then assign the access token to it.

```
$sfConfig = new SalesforceConfig();
$sfClient = new \Crunch\Salesforce\Client($sfConfig, new \GuzzleHttp\Client());

$sfClient->setAccessToken($accessToken);
```

### Performing an SOQL Query

[](#performing-an-soql-query)

This is a powerful option for performing general queries against your salesforce data. Simply pass a valid query to the search method and the resulting data will be returned.

```
$data = $sfClient->search('SELECT Email, Name FROM Lead LIMIT 10');
```

### Fetching a single record

[](#fetching-a-single-record)

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

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

### Creating and updating records

[](#creating-and-updating-records)

The process for creating and updating records is very similar and can be performed as follows. The createRecord method will return the id of the newly created record.

```
$data = $sfClient->createRecord('Lead', ['email' => 'foo@example.com', 'Company' => 'New test', 'lastName' => 'John Doe']);

$sfClient->updateRecord('Lead', '00WL0000008wVl1MDE', ['lastName' => 'Steve Jobs']);
// or with the above freshly created client
$sfClient->updateRecord('Lead', $data, ['lastName' => 'Steve Jobs']);
```

### Deleting records

[](#deleting-records)

Records can be deleted based on their id and type.

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

Errors
------

[](#errors)

If something goes wrong the library will throw an exception.

If its an authentication exception such as an expired token this will be as `Crunch\Salesforce\Exceptions\AuthenticationException`, you can get the exact details using the methods `getMessage` and `getErrorCode`.

All other errors will be `Crunch\Salesforce\Exceptions\RequestException`, the salesforce error will be in the message

```
try {

    $results = $sfClient->search('SELECT Name, Email FROM Lead Limit 10');
    print_r($results);

} catch (\Crunch\Salesforce\Exceptions\RequestException $e) {

    echo $e->getMessage();
    echo $e->getErrorCode();

} catch (\Crunch\Salesforce\Exceptions\AuthenticationException $e) {

    echo $e->getErrorCode();

}
```

###  Health Score

38

—

LowBetter than 84% of packages

Maintenance34

Infrequent updates — may be unmaintained

Popularity19

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity74

Established project with proven stability

 Bus Factor1

Top contributor holds 87.5% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~368 days

Recently: every ~825 days

Total

10

Last Release

669d ago

PHP version history (3 changes)1.0.3PHP &gt;=5.5

1.1.4PHP 8.3

1.1.5PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/04804917224430a60f5d739e5b6ae31d66fc03f32ad4b9c16392a64899444988?d=identicon)[owenkavanagh](/maintainers/owenkavanagh)

---

Top Contributors

[![ArthurGuy](https://avatars.githubusercontent.com/u/92837?v=4)](https://github.com/ArthurGuy "ArthurGuy (56 commits)")[![leeturner](https://avatars.githubusercontent.com/u/355292?v=4)](https://github.com/leeturner "leeturner (3 commits)")[![owenkavanagh-dmi](https://avatars.githubusercontent.com/u/187544928?v=4)](https://github.com/owenkavanagh-dmi "owenkavanagh-dmi (3 commits)")[![pinekta](https://avatars.githubusercontent.com/u/12654165?v=4)](https://github.com/pinekta "pinekta (1 commits)")[![richardTowers](https://avatars.githubusercontent.com/u/1696784?v=4)](https://github.com/richardTowers "richardTowers (1 commits)")

---

Tags

apirestoauth2salesforce

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/digitalmarketinginstitute-salesforce-api-php-wrapper/health.svg)

```
[![Health](https://phpackages.com/badges/digitalmarketinginstitute-salesforce-api-php-wrapper/health.svg)](https://phpackages.com/packages/digitalmarketinginstitute-salesforce-api-php-wrapper)
```

###  Alternatives

[omniphx/forrest

A Laravel library for Salesforce

2724.4M8](/packages/omniphx-forrest)[zoonman/linkedin-api-php-client

LinkedIn API PHP SDK with OAuth 2.0 &amp; CSRF support. Can be used for social sign in or sharing on LinkedIn. Examples. Documentation.

127704.0k](/packages/zoonman-linkedin-api-php-client)[xsolve-pl/salesforce-client

Salesforce REST client for PHP

3018.1k](/packages/xsolve-pl-salesforce-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
