To use Basic Authentication, you must first initialize an authentication object using Mautic\Auth\ApiAuth with a settings array specifying 'AuthMethod' => 'BasicAuth'. This authentication object is then passed to the newApi method when creating a specific API context (e.g., 'contacts').
Settings Array Keys:
AuthMethod: Must be 'BasicAuth' (or 'OAuth').userName: The username/login identifier for the Mautic user.password: The password for the user.apiUrl: The base URL of your Mautic instance.
Error Handling:
If credentials are incorrect or the wrong authentication method is used, the API will return an error response in the following format:
{
"errors": [
{
"code": 403,
"message": "access_denied: OAuth2 authentication required"
}
]
}
use Mautic\Auth\ApiAuth;
use Mautic\MauticApi;
// 1. Define settings
$settings = [
'AuthMethod' => 'BasicAuth',
'userName' => 'your_username',
'password' => 'your_password',
'apiUrl' => 'https://your-mautic-url.com/api',
];
// 2. Initialize the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings, $settings['AuthMethod']);
// 3. Create the API context and use it
$api = new MauticApi();
$contactApi = $api->newApi('contacts', $auth, $settings['apiUrl']);
// 4. Perform requests
$results = $contactApi->getList();