leadsengage/api-library

Leadsengage API 连接器库

dev-master 2018-05-17 13:34 UTC

This package is not auto-updated.

Last update: 2024-09-29 05:09:19 UTC


README

需求

  • PHP 5.3.7 或更高版本
  • cURL 支持

Leadsengage 设置

API必须在Leadsengage中启用。在Leadsengage中,转到配置页面(位于设置菜单中)并在API设置中启用Leadsengage的API。如果您打算使用基本身份验证,请确保您已启用它。您还可以在此选择要使用的OAuth协议。保存配置后,转到API凭证页面(位于设置菜单中)并创建一个新客户端。输入请求将从中发送的回调/重定向URI。点击应用然后将客户端ID和客户端密钥复制到将使用API的应用程序。

授权

获取访问令牌

第一步是获取授权。Leadsengage支持OAuth 1.0a和OAuth 2,但由管理员决定启用哪种。因此,最好在您的项目中有一个配置选项,让管理员选择您的代码应使用哪种方法。

<?php

// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';  

use Leadsengage\Auth\ApiAuth;

session_start();

$publicKey = '';
$secretKey = '';
$callback  = '';

// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
    'baseUrl'          => '',       // Base URL of the Leadsengage instance
    'version'          => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
    'clientKey'        => '',       // Client/Consumer key from Leadsengage
    'clientSecret'     => '',       // Client/Consumer secret key from Leadsengage
    'callback'         => ''        // Redirect URI/Callback URI for this script
);

/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken']        = $accessToken;
$settings['accessTokenSecret']  = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken']       = $refreshToken;
*/

// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);

// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization

// If the access token is expired, and a refresh token is set above, then a new access token will be requested

try {
    if ($auth->validateAccessToken()) {

        // Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
        // refresh token

        // $accessTokenData will have the following keys:
        // For OAuth1.0a: access_token, access_token_secret, expires
        // For OAuth2: access_token, expires, token_type, refresh_token

        if ($auth->accessTokenUpdated()) {
            $accessTokenData = $auth->getAccessTokenData();

            //store access token data however you want
        }
    }
} catch (Exception $e) {
    // Do Error handling
}

使用基本身份验证代替

与其使用OAuth,您可能更愿意选择使用BasicAuth。

以下是上述代码的基本Auth版本。

<?php

// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';  

use Leadsengage\Auth\ApiAuth;

session_start();

// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
    'userName'   => '',             // Create a new user       
    'password'   => ''              // Make it a secure password
);

// Initiate the auth object specifying to use BasicAuth
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings, 'BasicAuth');

// Nothing else to do ... It's ready to use.
// Just pass the auth object to the API context you are creating.

注意:如果凭证错误,将返回错误响应。

 array('error' => array(
       'code'    => 403,
       'message' => 'access_denied: OAuth2 authentication required' )
 )

API请求

现在您有了访问令牌和认证对象,您可以进行API请求。API被分解为上下文。

获取上下文对象

<?php

use Leadsengage\LeadsengageApi;

// Create an api context by passing in the desired context (Contacts, Forms, Pages, etc), the $auth object from above
// and the base URL to the Leadsengage server (i.e. http://my-leadsengage-server.com/api/)

$api = new LeadsengageApi();
$contactApi = $api->newApi('contacts', $auth, $apiUrl);

当前支持的上下文有

请参阅开发者文档

检索项目

上述所有上下文都支持以下检索项目函数

<?php

$response = $contactApi->get($id);
$contact = $response[$contactApi->itemName()];

// getList accepts optional parameters for filtering, limiting, and ordering
$response = $contactApi->getList($filter, $start, $limit, $orderBy, $orderByDir);
$totalContacts = $response['total'];
$contact = $response[$contactApi->listName()];

创建项目

<?php

$fields = $contactApi->getFieldList();

$data = array();

foreach ($fields as $field) {
    $data[$field['alias']] = $_POST[$field['alias']];
}

// Set the IP address the contact originated from if it is different than that of the server making the request
$data['ipAddress'] = $ipAddress;

// Create the contact
$response = $contactApi->create($data);
$contact = $response[$contactApi->itemName()];

编辑项目

目前,只有联系人支持此功能

<?php

$updatedData = array(
    'firstname' => 'Updated Name'
);

$response = $contactApi->edit($contactId, $updatedData);
$contact = $response[$contactApi->itemName()];

// If you want to create a new contact in the case that $contactId no longer exists
// $response will be populated with the new contact item
$response = $contactApi->edit($contactId, $updatedData, true);
$contact = $response[$contactApi->itemName()];

删除项目

<?php

$response = $contactApi->delete($contactId);
$contact = $response[$contactApi->itemName()];

错误处理

<?php

// $response returned by an API call should be checked for errors
$response = $contactApi->delete($contactId);

if (isset($response['error'])) {
    echo $response['error']['code'] . ": " . $response['error']['message'];
} else {
    // do whatever with the info
}

单元测试

在运行单元测试之前配置单元测试配置。测试会向Leadsengage实例发送真实的API请求。

  1. /tests/local.config.php.dist复制到/tests/local.config.php
  2. 在浏览器中打开API测试器,例如https:///api-library/apitester/index.php
  3. 填写您的Leadsengage实例的URL。
  4. 点击提交以将URL存储到会话中。
  5. 填写一个OAuth凭证并授权。
  6. 打开$_SESSION数组并将'access_token'复制到local.config.php文件。
  7. 然后运行vendor/bin/phpunit以运行测试。

修改此命令以运行特定测试:vendor/bin/phpunit --filter testCreateGetAndDelete tests/Api/NotesTest.php

修改此命令以运行一个类中的所有测试:vendor/bin/phpunit --filter test tests/Api/NotesTest.php