shayand / api-library
Requires
- php: >=5.3.7
- ext-curl: *
- psr/log: ~1.0
Requires (Dev)
- phpunit/phpunit: ~4.8|~5.0
- raveren/kint: ~0.9
This package is not auto-updated.
Last update: 2024-10-01 07:01:51 UTC
README
要求
- PHP 5.3.7 或更高版本
- cURL 支持
Shayand 设置
API 必须在 NextLead 中启用。在 NextLead 中,转到配置页面(位于设置菜单中),在 API 设置下启用 NextLead 的 API。如果您打算使用基本身份验证,请确保启用它。您还可以选择在此处使用的 OAuth 协议。保存配置后,转到 API 凭据页面(位于设置菜单中),并创建一个新客户端。输入请求将发送的回调/重定向 URI。点击应用,然后将客户端 ID 和客户端密钥复制到将使用 API 的应用程序。
授权
获取访问令牌
第一步是获取授权。NextLead 支持 OAuth 1.0a 和 OAuth 2,但由管理员决定启用哪种。因此,最好在项目中有一个配置选项,让管理员选择您的代码应使用哪种方法。
<?php // Bootup the Composer autoloader include __DIR__ . '/vendor/autoload.php'; use Shayand\Auth\ApiAuth; session_start(); $publicKey = ''; $secretKey = ''; $callback = ''; // ApiAuth->newAuth() will accept an array of Auth settings $settings = array( 'baseUrl' => '', // Base URL of the NextLead instance 'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value. 'clientKey' => '', // Client/Consumer key from NextLead 'clientSecret' => '', // Client/Consumer secret key from NextLead '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。
以下是上述代码的基本身份验证版本。
<?php // Bootup the Composer autoloader include __DIR__ . '/vendor/autoload.php'; use Shayand\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 Shayand\NextLeadApi; // 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 NextLead server (i.e. http://my-NextLead-server.com/api/) $api = new NextLeadApi(); $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 }
单元测试
在运行单元测试之前配置单元测试配置。测试将向 NextLead 实例发送真实 API 请求。
- 将
/tests/local.config.php.dist
复制到/tests/local.config.php
。 - 在浏览器中打开 API 测试器,例如 https:///api-library/apitester/index.php
- 填写您的 NextLead 实例的 URL。
- 点击提交以将 URL 存储到会话中。
- 填写 OAuth 凭据之一并进行授权。
- 打开 $_SESSION 数组并将 'access_token' 复制到 local.config.php 文件。
- 然后运行
vendor/bin/phpunit
以运行测试。
修改此命令以运行特定测试:vendor/bin/phpunit --filter testCreateGetAndDelete tests/Api/NotesTest.php
修改此命令以运行一个类中的所有测试:vendor/bin/phpunit --filter test tests/Api/NotesTest.php