mautic/api-library

Mautic API 连接器库

安装: 1,168,194

依赖项: 28

建议者: 0

安全性: 0

星标: 178

关注者: 38

分支: 122

开放问题: 48

4.0.0-beta 2024-08-30 13:02 UTC

README

codecov Latest Stable Version Total Downloads Latest Unstable Version License

All Contributors

使用 Mautic API 库

要求

  • PHP 8.0 或更高版本

安装 API 库

您可以使用以下命令安装 API 库

composer require mautic/api-library

注意:在安装此包之前,请确保您已安装了 PSR-18 HTTP 客户端,或者同时安装一个,例如 composer require mautic/api-library guzzlehttp/guzzle:^7.3

HTTP 客户端

借助 PSR-18 HTTP 客户端,我们与任何 HTTP 消息客户端解耦。这需要一个额外的包提供 psr/http-client-implementation。例如,要使用 Guzzle 7,只需要求 guzzlehttp/guzzle

composer require guzzlehttp/guzzle:^7.3

使用 php-http/discovery 自动发现已安装的 HTTP 客户端,但您也可以提供自己的 HTTP 客户端。

<?php

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

use GuzzleHttp\Client;
use Mautic\Auth\ApiAuth;

// Initiate an HTTP Client
$httpClient = new Client([
    'timeout'  => 10,
]);

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

Mautic 设置

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

授权

获取访问令牌

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

<?php

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

use Mautic\Auth\ApiAuth;

session_start();

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

// ApiAuth->newAuth() will accept an array of Auth settings
$settings = [
    'baseUrl'          => '',       // Base URL of the Mautic instance
    'version'          => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
    'clientKey'        => '',       // Client/Consumer key from Mautic
    'clientSecret'     => '',       // Client/Consumer secret key from Mautic
    '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。

以下是上述代码的 BasicAuth 版本。

<?php

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

use Mautic\Auth\ApiAuth;

session_start();

// ApiAuth->newAuth() will accept an array of Auth settings
$settings = [
    '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.

注意:如果凭据不正确,将返回错误响应。

 [
    'errors' => [
        [
            'code'    => 403,
            'message' => 'access_denied: OAuth2 authentication required',
            'type'    => 'access_denied',
        ],
    ],
 ];

API 请求

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

获取上下文对象

<?php

use Mautic\MauticApi;

// 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 Mautic server (i.e. http://my-mautic-server.com/api/)

$api        = new MauticApi();
$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 = [
    '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['errors'])) {
    foreach ($response['errors'] as $error) {
        echo $error['code'] . ": " . $error['message'];
    }
}

贡献

设置您的环境(自动)

为了快速入门,我们建议您使用 DDEV,它将自动为您设置一切。它会克隆 https://github.com/mautic/mautic,为您设置本地实例,并将 API 库测试连接到该实例。

要开始,请运行 ddev start!我们的首次运行体验将引导您完成设置。

设置您的环境(手动)

如果您想手动设置本地环境,请确保将 /tests/local.config.php.dist 复制到 /tests/local.config.php,并填写所需的设置。我们建议使用基本认证方法快速启动。

单元测试

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

  1. 请确保您已经按照上述步骤设置好了本地环境。
  2. 运行 composer test 来运行测试。

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

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

贡献者 ✨

感谢以下这些出色的人(emoji key

本项目遵循 all-contributors 规范。欢迎任何形式的贡献!