api library

2025-12-07 0 321

使用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实例。

  1. 确保使用上述步骤设置本地环境。
  2. 运行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

该项目遵循全企业规范。欢迎任何形式的贡献!

下载源码

通过命令行克隆项目:

git clone https://github.com/mautic/api-library.git

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

申明:本文由第三方发布,内容仅代表作者观点,与本网站无关。对本文以及其中全部或者部分内容的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。本网发布或转载文章出于传递更多信息之目的,并不意味着赞同其观点或证实其描述,也不代表本网对其真实性负责。

左子网 开发教程 api library https://www.zuozi.net/31870.html

常见问题
  • 1、自动:拍下后,点击(下载)链接即可下载;2、手动:拍下后,联系卖家发放即可或者联系官方找开发者发货。
查看详情
  • 1、源码默认交易周期:手动发货商品为1-3天,并且用户付款金额将会进入平台担保直到交易完成或者3-7天即可发放,如遇纠纷无限期延长收款金额直至纠纷解决或者退款!;
查看详情
  • 1、描述:源码描述(含标题)与实际源码不一致的(例:货不对板); 2、演示:有演示站时,与实际源码小于95%一致的(但描述中有”不保证完全一样、有变化的可能性”类似显著声明的除外); 3、发货:不发货可无理由退款; 4、安装:免费提供安装服务的源码但卖家不履行的; 5、收费:价格虚标,额外收取其他费用的(但描述中有显著声明或双方交易前有商定的除外); 6、其他:如质量方面的硬性常规问题BUG等。 注:经核实符合上述任一,均支持退款,但卖家予以积极解决问题则除外。
查看详情
  • 1、左子会对双方交易的过程及交易商品的快照进行永久存档,以确保交易的真实、有效、安全! 2、左子无法对如“永久包更新”、“永久技术支持”等类似交易之后的商家承诺做担保,请买家自行鉴别; 3、在源码同时有网站演示与图片演示,且站演与图演不一致时,默认按图演作为纠纷评判依据(特别声明或有商定除外); 4、在没有”无任何正当退款依据”的前提下,商品写有”一旦售出,概不支持退款”等类似的声明,视为无效声明; 5、在未拍下前,双方在QQ上所商定的交易内容,亦可成为纠纷评判依据(商定与描述冲突时,商定为准); 6、因聊天记录可作为纠纷评判依据,故双方联系时,只与对方在左子上所留的QQ、手机号沟通,以防对方不承认自我承诺。 7、虽然交易产生纠纷的几率很小,但一定要保留如聊天记录、手机短信等这样的重要信息,以防产生纠纷时便于左子介入快速处理。
查看详情

相关文章

猜你喜欢
发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务