使用Mautic api library
要求
- PHP 8.0或更新
安装api library
您可以使用以下命令安装api library :
composer require mautic/api-library
NB确保您在安装此软件包之前已安装了PSR-18 HTTP客户端或同时安装一个软件包,例如composer require mautic/api-library guzzlehttp/guzzle:^7.3 。
HTTP客户端
在PSR-18 HTTP客户端的帮助下,我们将与任何HTTP消息客户端分离。这需要一个额外的软件包,以提供PSR/HTTP-CLIENT-实现。例如,要使用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 }
改用基本身份验证
您可以简单地选择使用BasicAuth,而不是与Oauth乱七八糟。
这是上面代码的基本版本。
<?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请求
现在,您已经有了访问令牌和AUTH对象,可以做出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-m*au*t*ic-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://git*hu*b.c*om/mautic/mautic,为您设置本地实例,并将API库测试连接到该实例。
首先,运行ddev start !我们的首发经验将指导您完成设置。
设置您的环境(手动)
如果要手动设置本地环境,请确保复制/tests/local.config.php.dist to /tests/local.config.php ,并填写所需的设置。我们建议使用基本的身份验证方法快速起床和运行。
单位测试
在运行单元测试之前,请配置单元测试配置。测试FIRE REAL API请求对MAUTIC实例。
- 确保使用上述步骤设置本地环境。
- 运行
composer test以运行测试。
修改此命令以运行特定的测试: composer test -- --filter testCreateGetAndDelete tests/Api/NotesTest.php
修改此命令以在一个类中运行所有测试: composer test -- --filter test tests/Api/NotesTest.php
贡献者
谢谢这些好人(表情符号钥匙):
|
Zdeno Kuzmany |
Dlopez-Akalam |
Mollux |
玛蒂娜·索尔兹(Martina Scholz) |
约翰·林哈特(John Linhart) ? |
Marinus van Velzen |
皮埃尔·阿姆梅洛特(Pierre Ammeloot) ? |
|
马丁·沃里玛(MartinVooremäe) 配x |
该项目遵循全企业规范。欢迎任何形式的贡献!
