Sie können die API -Bibliothek mit dem folgenden Befehl installieren:
composer require mautic/api-library NB stellen Sie sicher composer require mautic/api-library guzzlehttp/guzzle:^7.3 Sie einen PSR-18-HTTP-Client installiert haben, bevor Sie dieses Paket installieren oder gleichzeitig einen gleichzeitig installieren.
Wir sind mit Hilfe des PSR-18-HTTP-Clients von jedem HTTP-Messaging-Client entkoppelt. Dies erfordert ein zusätzliches Paket, das PSR/HTTP-Client-Implementierung bereitstellt. Für die Verwendung von Guzzle 7 benötigen beispielsweise einfach guzzlehttp/guzzle :
composer require guzzlehttp/guzzle:^7.3Der installierte HTTP-Client wird mit Php-HTTP/Discovery automatisch entdeckt. Sie können jedoch auch Ihren eigenen HTTP-Client bereitstellen, wenn Sie möchten.
<?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. Die API muss in Mautic aktiviert sein. Gehen Sie innerhalb von MAUTIC zur Konfigurationsseite (befinden sich im Menü Einstellungen) und ermöglichen unter API -Einstellungen die API von MAUTIC. Wenn Sie beabsichtigen, die grundlegende Authentifizierung zu verwenden, stellen Sie sicher, dass Sie dies aktivieren. Sie können auch auswählen, welches OAuth -Protokoll Sie hier verwenden sollen. Gehen Sie nach dem Speichern der Konfiguration zur Seite der API -Anmeldeinformationen (im Menü Einstellungen) und erstellen Sie einen neuen Client. Geben Sie den Rückruf/Umleitungs -URI ein, aus dem die Anfrage gesendet wird. Klicken Sie auf Bewerben und kopieren Sie dann die Client -ID und das Client -Geheimnis in die Anwendung, die die API verwendet.
Der erste Schritt besteht darin, Autorisierung zu erhalten. Mautic unterstützt OAuth 1.0a und OAuth 2, es liegt jedoch an dem Administrator, zu entscheiden, welche aktiviert ist. Daher ist es am besten, in Ihrem Projekt eine Konfigurationsoption zu haben, damit der Administrator die Methode von Ihrem Code verwendet werden soll.
<?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
}Anstatt sich mit OAuth herumzuspielen, wählen Sie stattdessen einfach BasicAuth.
Hier ist die BasicAuth -Version des obigen Codes.
<?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.Hinweis: Wenn die Anmeldeinformationen falsch sind, wird eine Fehlerantwort zurückgegeben.
[
' errors ' => [
[
' code ' => 403 ,
' message ' => ' access_denied: OAuth2 authentication required ' ,
' type ' => ' access_denied ' ,
],
],
];Nachdem Sie ein Zugriffstoken und das Auth -Objekt haben, können Sie API -Anfragen stellen. Die API ist in Kontexte unterteilt.
<?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 );Unterstützte Kontexte sind derzeit:
Siehe die Entwicklerdokumentation.
Alle oben genannten Kontexte unterstützen die folgenden Funktionen zum Abrufen von Elementen:
<?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 ' ];
}
}Um schnell loszulegen, empfehlen wir Ihnen, DDEV zu verwenden, das die Dinge automatisch für Sie einstellt. Es kloniert https://github.com/mutic/mutic, richtet eine lokale Instanz für Sie ein und verbindet die API -Bibliothekstests mit dieser Instanz.
Um loszulegen, rennen Sie ddev start ! Unsere Erlebnisserfahrung wird Sie durch das Setup führen.
Wenn Sie Ihre lokale Umgebung manuell einrichten möchten, stellen Sie sicher, dass Sie /tests/local.config.php.dist to /tests/local.config.php kopieren und die erforderlichen Einstellungen eingeben. Wir empfehlen, die grundlegende Authentifizierungsmethode zu verwenden, um schnell auf dem Betrieb zu gehen.
Konfigurieren Sie die Konfiguration der Unit -Tests, bevor Sie die Unit -Tests ausführen. Die Tests feuern echte API -Anfragen zu einer mauischen Instanz.
composer test aus, um die Tests auszuführen. Ändern Sie diesen Befehl, um einen bestimmten Test auszuführen: composer test -- --filter testCreateGetAndDelete tests/Api/NotesTest.php
Ändern Sie diesen Befehl, um alle Tests in einer Klasse auszuführen: composer test -- --filter test tests/Api/NotesTest.php
Vielen Dank an diese wunderbaren Menschen (Emoji -Schlüssel):
Zdeno Kuzmany | DLOPEZ-AKALAM | Mollux | Martina Scholz | John Linhart ? | Marinus van Velzen | Pierre Ammeloot ? |
Martin Vooremäe |
Dieses Projekt folgt der All-Contributors-Spezifikation. Beiträge jeglicher Art willkommen!