承接 chorton/salesforce-api-php-wrapper 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

chorton/salesforce-api-php-wrapper

Composer 安装命令:

composer require chorton/salesforce-api-php-wrapper

包简介

A library for interacting with the Salesforce REST API and managing the OAuth flow. Forked from https://github.com/crunch-accounting/salesforce-api-php-wrapper

README 文档

README

Current Version License Scrutinizer Travis

Salesforce PHP Library

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!

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

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

Getting an OAuth Token:

With User interaction: 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', 'v37.0');

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();

}

When having the username and password: To use this method you also need the security token to be appended to the password. Keep in mind this method is to be used as a replacement for the old API Key workflow.

$sfClient = \Crunch\Salesforce\Client::create('https://test.salesforce.com/', 'clientid', 'clientsecret');
$sfClient->login('username', 'passwordAndSecurityTokenAppended');

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

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';
    }
    
    /**
     * Version of the API you wish to use
     * @return string
     */
    public function getVersion()
    {
        return 'v37.0';
    }
}

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

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 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 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 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']);

###Deleting records Records can be deleted based on their id and type.

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

##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();
    
}

chorton/salesforce-api-php-wrapper 适用场景与选型建议

chorton/salesforce-api-php-wrapper 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.47k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2020 年 02 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「rest」 「api」 「oauth2」 「salesforce」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 chorton/salesforce-api-php-wrapper 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 chorton/salesforce-api-php-wrapper 我们能提供哪些服务?
定制开发 / 二次开发

基于 chorton/salesforce-api-php-wrapper 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 3.47k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 18
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 22
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2020-02-21