GithubHelp home page GithubHelp logo

mailchimp-api-php's Introduction

PHP library for v3 of the Mailchimp API

This library provides convenient wrapper functions for Mailchimp's REST API. The API is documented here.

Requirements

  • PHP 5.4.0 or greater (7.0 or greater if you wish to use phpunit)
  • Composer
  • Guzzle

Installation

Dependencies are managed by Composer. After installing Composer, run the following command from the library root:

composer install --no-dev --ignore-platform-reqs

Or to install with phpunit:

composer install

Usage

Get your account information

A basic test to confirm the library is set up and functional.

With OAuth Access token

<?php
require 'PATH_TO_LIBRARY/mailchimp-api-php/vendor/autoload.php';

// Instantiate MailchimpApiInterface
$authentication_settings = [
  'access_token' => 'YOUR_ACCESS_TOKEN',
  'data_center' => 'YOUR_DATA_CENTER',
  'api_user' => 'oauth',
];

// Use Mailchimp2 class for OAuth access_token.
$api_class = new Mailchimp2($authentication_settings);

// Instantiate a MailchimpApiUser or a class that extends it (ie. MailchimpLists, MailchimpSignups, etc..)
$mailchimp = new MailchimpApiUser($api_class);

// Get the account details of the authenticated user.
$response = $mailchimp->getAccount();

// Output the account details.
if (!empty($response) && isset($response->account_id)) {
  echo "ID: {$response->account_id}\n"
  . "Name: {$response->account_name}\n";
}

With API Key

require 'PATH_TO_LIBRARY/mailchimp-api-php/vendor/autoload.php';

// Instantiate MailchimpApiInterface
$authentication_settings = [
  'api_key' => 'YOUR_API_KEY',
  'api_user' => 'api_key',
];

// Use Mailchimp class for api_key.
$api_class = new Mailchimp($authentication_settings);

// Instantiate a MailchimpApiUser or a class that extends it (ie. MailchimpLists, MailchimpSignups, etc..)
$mailchimp = new MailchimpApiUser($api_class);

// Get the account details of the authenticated user.
$response = $mailchimp->getAccount();

// Output the account details.
if (!empty($response) && isset($response->account_id)) {
  echo "ID: {$response->account_id}\n"
  . "Name: {$response->account_name}\n";
}ject = new MailchimpApiUser($api_class, $http_options);

Get lists and their interest categories

A more complicated example that takes the response from one API call and uses that data to make another.

<?php
require 'PATH_TO_LIBRARY/mailchimp-api-php/vendor/autoload.php';

$authentication_settings = [
  'access_token' => 'YOUR_ACCESS_TOKEN',
  'data_center' => 'YOUR_DATA_CENTER',
  'api_user' => 'oauth',
];
$api_class = new Mailchimp2($authentication_settings);

$mailchimp_lists = new Mailchimp\MailchimpLists($api_class);

// Get all lists.
$response = $mailchimp_lists->getLists();

if (!empty($response) && isset($response->lists)) {
  foreach ($response->lists as $list) {
    // Output the list name.
    echo "List name: {$list->name}\n";

    // Get the list's interest categories.
    $interests = $mailchimp_lists->getInterestCategories($list->id);

    // Output the names of the list's interest categories.
    if (!empty($interests) && isset($interests->categories)) {
      foreach ($interests->categories as $category) {
        echo "Interest category: {$category->title}\n";
      }
    }
  }
}

Testing

This library includes a PHPUnit test suite.

Running PHPUnit tests

Add Composer's vendor directory to your PATH by adding the following line to your profile. This is dependent on your system, but on a Linux or Mac OSX system using Bash, you'll typically find the file at ~/.bash_profile.

export PATH="./vendor/bin:$PATH"

Bash example:

echo 'export PATH="./vendor/bin:$PATH"' >> ~/.bash_profile
source ~/.bash_profile

Then run PHPUnit:

phpunit

mailchimp-api-php's People

Contributors

a-fro avatar amyvs avatar anthonyrw avatar aprice42 avatar bangpound avatar darthsteven avatar eleonel avatar greg-boggs avatar mariacha avatar megachriz avatar mortenson avatar nrackleff avatar pfrenssen avatar primsi avatar ruscoe avatar szeidler avatar tamarpe avatar taz77 avatar tbaumgard avatar tim-qualtim avatar unclegcb avatar w3guy avatar welcomattic avatar xeno010 avatar xenophyle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mailchimp-api-php's Issues

Add more campaign report options

It would be helpful to have access to full range of mailchimp campaign reports. I've added my own function to the library as such:

`/**

*/
public function getCampaignReport($campaign_id, $type, $parameters = []) {
$tokens = [
'campaign_id' => $campaign_id,
];

return $this->request('GET', '/reports/{campaign_id}/' . $type, $tokens, $parameters);

}`

Function for unscheduling a campaign

Can you consider adding this to the library please?

`/**

return $this->request('POST', '/campaigns/{campaign_id}/actions/unschedule', $tokens, NULL);

}`

ecommerce tests are failing

1) Mailchimp\Tests\MailchimpEcommerceTest::testGetStore
Failed asserting that null matches expected 'GET'.

/Users/ruscoe/Sites/mandrill7/sites/all/libraries/mailchimp/tests/MailchimpEcommerceTest.php:32

2) Mailchimp\Tests\MailchimpEcommerceTest::testAddStore
Failed asserting that null matches expected 'POST'.

/Users/ruscoe/Sites/mandrill7/sites/all/libraries/mailchimp/tests/MailchimpEcommerceTest.php:50

3) Mailchimp\Tests\MailchimpEcommerceTest::testGetCustomer
Failed asserting that null matches expected 'GET'.

/Users/ruscoe/Sites/mandrill7/sites/all/libraries/mailchimp/tests/MailchimpEcommerceTest.php:317

4) Mailchimp\Tests\MailchimpEcommerceTest::testAddCustomer
Failed asserting that null matches expected 'POST'.

/Users/ruscoe/Sites/mandrill7/sites/all/libraries/mailchimp/tests/MailchimpEcommerceTest.php:335

5) Mailchimp\Tests\MailchimpEcommerceTest::testGetOrder
Failed asserting that null matches expected 'GET'.

/Users/ruscoe/Sites/mandrill7/sites/all/libraries/mailchimp/tests/MailchimpEcommerceTest.php:410

6) Mailchimp\Tests\MailchimpEcommerceTest::testAddOrder
Failed asserting that null matches expected 'POST'.

/Users/ruscoe/Sites/mandrill7/sites/all/libraries/mailchimp/tests/MailchimpEcommerceTest.php:442

Parameter issue with php 5.4

Noticed that when I am getting templates from Mailchimp, only 10 templates are being received . After debugging, I noticed that the & character gets converted to &.

Publish library on Packagist

Would it be possible for you guys to publish this library on Packagist so it can be included via Composer? I run my Drupal site dependencies via Composer and Drupal Composer Manager module, just makes life easy.

Schedule Campaign variables

$timewarp & $batch_delivery should have default values i think...

public function schedule($campaign_id, $schedule_time, $timewarp = FALSE, $batch_delivery = FALSE, $parameters = [], $batch = FALSE) {
$tokens = [
'campaign_id' => $campaign_id,
];

$parameters += [
  'schedule_time' => $schedule_time,
  'timewarp' => $timewarp,
  'batch_delivery' => $batch_delivery,
];

return $this->request('POST', '/campaigns/{campaign_id}/actions/schedule', $tokens, $parameters, $batch);

}

getCampaignContent method (Patch attached)

Hi everyone,

Thanks so much for the awesome work getting the new API Library and Drupal module up to snuff.

I was in need of a getter to the setCampaignContent method, as we have an archive page on the site where we occasionally send users who missed an email.

It was pretty simple to implement, so hopefully this will be an easy addition to this awesome lib.

Thanks!

Erik

mailchimp-api_getCampaignContent.patch.txt

Lists null intermittently

When I run this code locally, most of the time I get NULL in $myLists but sometimes I get the lists

$list = new Mailchimp\MailchimpLists($key);
$myLists = $list->getLists(['count'=>30]);

MailchimpLists needs a function to add multiple users to a segment

See https://www.drupal.org/node/2820269#comment-12130538.

The Drupal module, in order to add users to a segment via VBO, needs to be able to call the "Batch add/remove list members to static segment" method: http://developer.mailchimp.com/documentation/mailchimp/reference/lists/segments/#create-post_lists_list_id_segments_segment_id

MailchimpLists.php doesn't include a function for calling that endpoint. My patch in the Drupal issue queue adds one.

Wrong version

Mailchimp.php still lists version 1.0.5

const VERSION = '1.0.5';

MailchimpLists->updateSegment() has Improper Parameters

According to the documentation for adding/removing users to a static segment the parameters members_to_add and members_to_remove are the only (optional) parameters to be used towards this execution.

The only assured parameter is the name of the segment - which should only be passed in when creating a new segment.

I've noticed this using Drupal 7.55 and MailChimp 7.x-4.8.

When attempting to rewrite the mailchimp_segment_batch_add_subscribers() function to have the proper parameters as specified in the above documentation I was returned with zero errors and zero successes.

Logging Mailchimp->handleRequest() returns the following:

Method: PATCH

URI: 'https://us15.api.mailchimp.com/3.0/lists/{list_id redacted}/segments/{segment_id redacted}'

Options:
Array
(
    [headers] => Array
        (
            [Authorization] => apikey {api_key redacted}
        )

    [json] => stdClass Object
        (
            [members_to_add] => Array
                (
                    [0] => {valid email redacted}
                )
            [name] => Freddie's peeps
        )
)

Missing updating, deleting, and adding an interest of a group,

There are no functionalities for all those operations for interests of a group beside get.
Example of an adding one:

  public function addInterest($list_id, $group_id, $name, $parameters = []) {
    $tokens = [
      'list_id' => $list_id,
      'group_id' => $group_id,
    ];

    $parameters += [
      'name' => $name,
    ];

    return $this->request('POST', '/lists/{list_id}/interest-categories/{group_id}', $tokens, $parameters);
  }

Use Guzzle's requestAsync() and \GuzzleHTTP\Pool for API write requests

According to MailChimp API Best Practices, they recommend that API calls be made as async background processes. This is to avoid times when the user might experience a long wait, as a response is expected from the MC API that might take a few seconds.

Currently this Guzzle HTTP library implementation uses request() exclusively, and as such all requests including Update and Create, are done synchronously, which means the end user will be required to wait for the response and its result. This leads to poor user experience, and in my case, I was seeing GuzzleHTTP reporting open connections of 15 seconds to the API. (This might be fixable just by adding Connection: close to our headers array, too; however I think there are advantages to persistent connections, and even better performance can be gained when used in conjunction with background tasks.)

I recognize we can also use batch requests to help improve performance, but those requests still rely on user interaction and result in a blocking call to the external resource (MailChimp). I've seen some requests in the MC Dashboard reported as taking 3-5 seconds to process, which for an e-commerce site is a potentially problematic amount of time to wait.

Therefore, any non-read requests to the API (PUT, POST, PATCH) should create or merge with a \GuzzleHttp\Pool instance, which in turn calls requestAsync(), thereby allowing the MC API PHP library to handle updating and creation of carts and orders without blocking user requests.

v2 is undetectable by Drupal 7 module

The v2.0.0-package.zip file does not include composer.json, which the Drupal 7 module relies on for version detection. Please add that file to the zip if possible.

Develop examples in documentation

Build example calls of the various methods, some of which are complex. Provide examples in a markdown file that someone can use to see how they parameters would be constructed.

Coding standards

  • Ensure function arguments match names in MailChimp API
  • Ensure function docs are consistently formatted
  • Ensure short array format is used consistently ([] not array())

Abstract Away HTTP Client Dependency

I am suggesting any HTTP client to be used should be it's own (wrapper) class that extends an interface which contains a handleRequest() method that all HTTP client must implement.

The following code

if ($this->use_curl) {
   return $this->handleRequestCURL($method, $this->endpoint . $path, $options, $parameters, $returnAssoc);
    }
    else {
      return $this->handleRequest($method, $this->endpoint . $path, $options, $parameters, $returnAssoc);
    }

will now become just

   return $this->handleRequest($method, $this->endpoint . $path, $options, $parameters, $returnAssoc);

By doing this, therefore means an instance of an HTTP client will be passed to the MailChimp class constructor or a special method to include the HTTP client dependency.

Why am i proposing this?

Because in WordPress, it is bundled with it own HTTP client and would love to use that instead.

Converting to short array syntax

Since this API requires Guzzle 6.x and hence requires PHP >= 5.4. Would there be any issues converting to the short array syntax? Makes for quicker coding and easier to read IMHO.

I will be glad to do it if you guys don't have a problem with it.

Adding products via batch

As far as I can see, adding products in batches isn't supported. Is there a reason for this?

According to the Mailchimp support, it is supported by their API.

Handle MailChimp exception classes with cURL

There are a few places where MailChimp error exceptions are not being handled by cURL because we expect them to be handled with Guzzle. We need to update MailchimpLists.php and Mailchimp.php to handle these.

throw new MailchimpAPIException($e->getResponse()

to this:

throw new MailchimpAPIException($e->getMessage()

Campaign Send checklist function

Thanks for adding all the features i've been asking for. Here's another one that is actually pretty important. The reason this one is helpful is to determine whether the campaign is actually ready to send prior to sending it. The api documentation will return an is_ready value as well as a summary list of issues if any. In some cases on our end, we have tried to send a campaign that either did not have any subscribers to send to or the from_email for the campaign was using a domain that had not been verified. The latter is an issue recurring issue for us as we manage campaigns for our clients that have their own email as the from email so the email domain needs to be verified or else mailchimp won't allow the campaign to send. I believe this would be the case for scheduled campaigns as well.

`/**

return $this->request('GET', '/campaigns/{campaign_id}/send-checklist', $tokens, NULL);

}`

MailchimpCURLClient response check is wrong with campaign

Using Drupal 7 + mailchimp module 7.x-4.7 in a 5.4.45 PHP environment.

Once you fix all the composer and module php 5.5 requirement stuff you can install and use.

But creating a campaign in Drupal result in nothing except this notice
Notice : Undefined property: stdClass::$detail dans Mailchimp\MailchimpCURLClient->request() (ligne 98 dans /data/guillaume/git/avise-13-001/drupal/sites/all/libraries/mailchimp/src/MailchimpCURLClient.php).

Looking around this code i found this comment a1a6a9f

The problem seems to be that the response of a campaign creation contains a status (send, saved, etc) which is not what we want to test here. And so all the rest is stopped because of the exception.

Please add a license to this package

Hello, thanks for all your work, it is really appreciated. I am with the Backdrop CMS team (Backdrop is a fork of Drupal), and I ported Mailchimp for Backdrop, based on the Drupal module. I am in the process of updating the code to the latest Mailchimp Drupal version, but Backdrop has by principle encouraged bundling external libraries directly into contrib modules to ease the user experience, more so in recent times, since after my initial port, which used Libraries module. I couldnt find any statement about licencing on your libraries so thought I'd ask if this is permitted. Or if you had any objection to this technically of philosophically. Would be grateful for your thoughts.
Thanks.

PHP 5.3 support?

Thank you for maintaining the mailchimp-api-php library :)

Release v1.0.3 is broken with mailchimp module for drupal 7.x-4.4
Major PHP error expecting different [ { brackets tested in php 5.3 (whom still is officially supported)

git clone from master, then composer install does work nicely still
Solution make a new release.

Allow users to pass options to the http client

Allowing users to pass options to the http client seems like a desirable feature because many environments require some specific configuration. For example corporate networks typically won't allow unrestricted access to the internet. Allowing users to configure Guzzle to use a proxy server would be very helpful in those cases.

I've considered several approaches to this problem:

  1. inject the Client object instead of instantiating it inside the Mailchimp object
  2. introduce a getter for the client object
  3. repurpose the 3rd constructor argument

The first option would make using this library more cumbersome and break backwards compatibility.

The second option will work but it's cleaner not to expose the Guzzle client publically.

So I'll follow up with a pull request that implements the third option. Any feedback is welcome!

Issue with MailchimpLists->updateSegment

While reviewing how the Drupal mailchimp module adds subscribers to lists, I see that mailchimp_segment_batch_add_subscribers calls $mc_lists->updateSegment($list_id, $segment_id, $matched_segment->name, $parameters);. I'm trying to call the API's updateSegment independently from the Drupal module to add a subscriber to a static segment, but it doesn't work.

I'd prefer to use the Segment Members REST service instead. Is there a reason that you're using the Update Segment resource, rather than the Segment Members sub-resource? If I create a PR to add that sub-resource to the PHP API, will you review and accept it?

MailchimpAutomations?

Hey team ThinkShout! Have you discussed adding support for automations to the library?

If I were to work on a pull request and follow the same patterns/standards you've established, would you consider it? Currently, we only need support for adding subscribers to a workflow, though I could take a look at other likely automation endpoint candidates for inclusion.

Eventually, I'd be interested in helping with a mailchimp_automations Drupal submodule, though that's probably more of a commitment than I can make at this time.

Thanks for your consideration!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.