Mailchimp Marketing PHP SDK

repository·master·Indexed 41 days ago

https://github.com/mailchimp/mailchimp-marketing-php

The official PHP client library for the Mailchimp Marketing API. It provides a structured way to programmatically interact with Mailchimp's marketing features, including campaigns, automations, lists, members, and ecommerce. Supports PHP 7.2 or above and offers authentication via Basic Auth or OAuth2.

Tokens
9.4K
Snippets
63
Records
67
Agent score
50%

What's inside Mailchimp

  1. Quick Start with Mailchimp Marketing PHP

    master

    To get started, ensure you are using PHP 7.2 or above. Initialize the ApiClient, configure it with your credentials, and make a test call using the ping endpoint.

    Note that you must provide a server prefix (e.g., us19) so the client can determine the correct host URL.

    require_once('/path/to/MailchimpMarketing/vendor/autoload.php');
    
    $mailchimp = new MailchimpMarketing\ApiClient();
    
    $mailchimp->setConfig([
      'apiKey' => 'YOUR_API_KEY',
      'server' => 'YOUR_SERVER_PREFIX'
    ]);
    
    $response = $mailchimp->ping->get();
    print_r($response);
  2. Install the Mailchimp Marketing PHP SDK

    master

    You can install the SDK using Composer via Packagist, which is the recommended method, or by cloning the repository manually.

    Using Composer

    Run the following command in your terminal:

    composer require mailchimp/marketing

    Alternatively, add this to your composer.json file:

    {
      "require": {
        "mailchimp/marketing": "*"
      }
    }

    Then run composer install to install dependencies.

    Manual Installation

    1. Clone the repository:
    git clone git@github.com:mailchimp/mailchimp-marketing-php.git
    1. Install dependencies in the project root:
    composer install
    1. Manually include the autoloader in your project:
    require_once('/path/to/MailchimpMarketing/vendor/autoload.php');
  3. Handle detailed API responses with WithHttpInfo methods

    master

    For most methods in AutomationsApi, there is a corresponding WithHttpInfo version (e.g., pauseWorkflowEmailWithHttpInfo). Use these when you need access to the full HTTP response metadata or need to catch and inspect ApiException objects specifically.

    Example pattern:

    • pauseWorkflowEmail($id, $email_id): Returns the decoded JSON response body directly.
    • pauseWorkflowEmailWithHttpInfo($id, $email_id): Returns the decoded JSON response body but allows for more granular error handling via ApiException.
  4. Configure Authentication (Basic Auth or OAuth2)

    master

    The ApiClient supports two authentication methods. For both methods, you must include the server key (e.g., us19) in the configuration array.

    Basic Auth

    Use your Mailchimp API Key:

    $mailchimp->setConfig([
      'apiKey' => 'YOUR_API_KEY',
      'server' => 'YOUR_SERVER_PREFIX'
    ]);

    OAuth2

    Use your OAuth2 Access Token:

    $mailchimp->setConfig([
      'accessToken' => 'YOUR_ACCESS_TOKEN',
      'server' => 'YOUR_SERVER_PREFIX'
    ]);
    // Basic Auth Example
    $mailchimp->setConfig([
      'apiKey' => 'YOUR_API_KEY',
      'server' => 'YOUR_SERVER_PREFIX'
    ]);
    
    // OAuth2 Example
    $mailchimp->setConfig([
      'accessToken' => 'YOUR_ACCESS_TOKEN',
      'server' => 'YOUR_SERVER_PREFIX'
    ]);
  5. Reference the Mailchimp Marketing API Endpoints

    master

    The Mailchimp Marketing PHP SDK provides access to a wide range of API endpoints. All URIs are relative to https://server.api.mailchimp.com/3.0. The SDK methods correspond to the following endpoint mappings:

    Account & Apps

    • accountExport.getAccountExports: /account-exports/{export_id}
    • accountExports.listAccountExports: /account-exports
    • accountExports.createAccountExport: /account-exports
    • authorizedApps.list: /authorized-apps
    • authorizedApps.get: /authorized-apps/{app_id}

    Automations

    • automations.list: /automations
    • automations.get: /automations/{workflow_id}
    • automations.create: /automations
    • automations.archive: /automations/{workflow_id}/actions/archive
    • automations.deleteWorkflowEmail: /automations/{workflow_id}/emails/{workflow_email_id}
    • automations.updateWorkflowEmail: /automations/{workflow_id}/emails/{workflow_email_id}
    • automations.pauseAllEmails: /automations/{workflow_id}/actions/pause-all-emails
    • automations.startAllEmails: /automations/{workflow_id}/actions/start-all-emails

    Campaigns & Folders

    • campaigns.list: /campaigns
    • campaigns.get: /campaigns/{campaign_id}
    • campaigns.create: /campaigns
    • campaigns.send: /campaigns/{campaign_id}/actions/send
    • campaigns.schedule: /campaigns/{campaign_id}/actions/schedule
    • campaignFolders.list: /campaign-folders
    • campaignFolders.create: /campaign-folders

    Ecommerce

    • ecommerce.stores: /ecommerce/stores
    • ecommerce.getStore: /ecommerce/stores/{store_id}
    • ecommerce.orders: /ecommerce/orders
    • ecommerce.getStoreProduct: /ecommerce/stores/{store_id}/products/{product_id}
    • ecommerce.getStoreCustomer: /ecommerce/stores/{store_id}/customers/{customer_id}

    Lists & Members

    • lists.getAllLists: /lists
    • lists.getList: /lists/{list_id}
    • lists.addListMember: /lists/{list_id}/members
    • lists.getListMember: /lists/{list_id}/members/{subscriber_hash}
    • lists.updateListMember: /lists/{list_id}/members/{subscriber_hash}
    • lists.deleteListMember: /lists/{list_id}/members/{subscriber_hash}
    • lists.createSegment: /lists/{list_id}/segments

    Reports & Analytics

    • reports.getCampaignReport: /reports/{campaign_id}
    • reports.getCampaignOpenDetails: /reports/{campaign_id}/open-details
    • reports.getCampaignClickDetails: /reports/{campaign_id}/click-details
    • reporting.getLandingPageReport: /reporting/landing-pages/{outreach_id}

    Note: This is a partial list of available endpoints. Refer to the full SDK documentation for the complete enumeration.

  6. Handle API errors with ApiException

    master

    When an API request fails, the SDK throws a MailchimpMarketing\ApiException. This exception contains detailed information about the failed HTTP request, allowing you to inspect the error response from Mailchimp's servers.

    You can catch this exception to retrieve the HTTP status code, the response headers, and the response body (which is typically a JSON object containing error details).

    try {
        // Your Mailchimp API call here
    } catch (\MailchimpMarketing\ApiException $e) {
        echo 'Error Message: ' . $e->getMessage() . PHP_EOL;
        echo 'HTTP Status Code: ' . $e->getCode() . PHP_EOL;
        
        // Get the decoded JSON body containing error details
        $errorBody = $e->getResponseBody();
        print_r($errorBody);
    
        // Get response headers if needed
        $headers = $e->getResponseHeaders();
    }
  7. Handle API errors and exceptions

    master

    The SDK uses ApiException to signal errors returned by the Mailchimp API. When an API request fails (status code outside the 200-299 range), an ApiException is thrown.

    To access the detailed error response provided by Mailchimp (which often contains specific error messages and codes in JSON format), you should catch the ApiException and call getResponseBody() on it.

    Example:

    try {
        $response = $campaignsApi->update($campaign_id, $body);
    } catch (ApiException $e) {
        // The response body contains the parsed JSON error from Mailchimp
        $errorDetails = $e->getResponseBody();
        print_r($errorDetails);
    }