Git Product home page Git Product logo

mailchimp-api-v3's Introduction

Mailchimp API v3 - PHP Wrapper Build Status

Installation

Add the following to your composer.json

{
    "require": {
        "pacely/mailchimp-apiv3": "dev-master"
    }
}

Laravel Users

We've added some classes to help Laravel 5 users make use of the library with ease.

Service Provider

You can register our service provider in your app.php config file.

// config/app.php
'providers' => [
    ...
    Mailchimp\MailchimpServiceProvider::class
]

Facade

If you prefer facades, make sure you add this as well:

// config/app.php
'aliases' => [
    ...
    'MC' => Mailchimp\MailchimpFacade::class
]

NOTE: Make sure not to register the facade with the Mailchimp alias, as that could potentially clash with the base class.

Configuration

There are only one configuration option you need to fill in. Publish the config by running:

php artisan vendor:publish

Now, the config file will be located under config/mailchimp.php:

<?php

return [

    /*
    |--------------------------------------------------------------------------
    | Mailchimp API key
    |--------------------------------------------------------------------------
    |
    | To obtain an API key, go to mailchimp.com under your profile
    | you will find Extras -> API keys. Paste the key below.
    |
    */
    'apikey' => ''
];

Usage

There's one method to rule them all:

request($resource, $arguments = [], $method = 'GET') // $arguments is used as POST data or GET parameters, depending on the method used.

But its clever enough to map these calls aswell:

get($resource, array $options = [])
head($resource, array $options = [])
put($resource, array $options = [])
post($resource, array $options = [])
patch($resource, array $options = [])
delete($resource, array $options = [])

Pagination

We use offset and count in the query string to paginate data, because it provides greater control over how you view your data. Offset defaults to 0, so if you use offset=1, you'll miss the first element in the dataset. Count defaults to 10.

Source: http://kb.mailchimp.com/api/article/api-3-overview

Filtering

Most endpoints don't currently support filtering, but we plan to add these capabilities over time. Schemas will tell you which collections can be filtered, and what to include in your query string.

Source: http://kb.mailchimp.com/api/article/api-3-overview

Partial Response

To cut down on data transfers, pass a comma separated list of fields to include or exclude from a certain response in the query string. The parameters fields and exclude_fields are mutually exclusive and will throw an error if a field isn't valid in your request.

Source: http://kb.mailchimp.com/api/article/api-3-overview

Behind Proxy

If you are behind a proxy, you can use setProxy directly on the class.

setProxy(host : string, port : int, [ssl : bool = false], [username = null], [password = null]);

See the example.

Examples

Collection object

All queries will return an instance of the Illuminate\Support\Collection object, which is really easy to work with. If you don't want to use the Collection object however, you can transform it into an array using $result->toArray().

$mc = new Mailchimp('<api-key>', '<guzzle-options[array]>');

// Get 10 lists starting from offset 10 and include only a specific set of fields
$result = $mc->request('lists', [
    'fields' => 'lists.id,lists.name,lists.stats.member_count',
    'offset' => 10,
    'count' => 10
]);

// Will fire this query: 
// GET https://us1.api.mailchimp.com/3.0/lists?fields=lists.id,lists.name,lists.stats.member_count&count=10

// Returns object(Illuminate\Support\Collection)
var_dump($result);

// Returns the first item
var_dump($result->first());

// Returns 3 items
var_dump($result->take(3));

// Returns a JSON string
var_dump($result->toJson());

// Returns an array
var_dump($result->toArray());

You can use a simple foreach/for loop or use the built in each(callable $callback) provided by our Collection object to loop through your items.

$result->each(function ($item) {
    echo $item['name'].' ('.$item['stats']['member_count'].')'.PHP_EOL;
});

There's alot more you can do with the Collection object.

Create lists

// All these fields are required to create a new list.
$result = $mc->post('lists', [
    'name' => 'New list',
    'permission_reminder' => 'You signed up for updates on Greeks economy.',
    'email_type_option' => false,
    'contact' => [
        'company' => 'Doe Ltd.',
		'address1' => 'DoeStreet 1',
		'address2' => '',
		'city' => 'Doesy',
		'state' => 'Doedoe',
		'zip' => '1672-12',
		'country' => 'US',
		'phone' => '55533344412'
    ],
    'campaign_defaults' => [
        'from_name' => 'John Doe',
        'from_email' => '[email protected]',
        'subject' => 'My new campaign!',
        'language' => 'US'
    ]
]);

Subresources

$result = $mc->get('lists/e04d611199', [
    'fields' => 'id,name,stats.member_count'
]);

Proxy

$mc->setProxy('https://127.0.0.1', 10, true, 'username', 'password');

$result = $mc->get('lists/e04d611199', [
    'fields' => 'id,name,stats.member_count'
]);

Further documentation

You should read through Mailchimp's API v3 documentation (I know, it's pretty rough. Should get better soon.). To find out which resources is available, take a look at the JSON API Schema for Mailchimp.

mailchimp-api-v3's People

Contributors

chrisrm avatar dominicmartineau avatar erictendian avatar limenet avatar stefandoorn 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  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

mailchimp-api-v3's Issues

New release

Hi,

The last changes (e.g. setting Guzzle options + fixing multiple calls in a row reusing the object) are not in a release yet, so I need to require dev-master (which I don't like for consecutive updates). Could you file a new release consisting of these helpful functions?

Thanks!

Laravel Facade

There is a bug in the MailchimpFacade.php - needs to return "Mailchimp\Mailchimp" rathern than just "Mailchimp"

Exception handling - is this package maintained?

Hi, is this package still maintained?

I'll gladly submit a PR with some exception handling if it is.

(that is, throwing more exception types instead of PHP's base \Exception, or at least assigning the Exception with the response data as an array instead of a JSON encoded string).

Schema describes array, object found instead

It seems that your wrapper somewhere converts arrays to objects which cause trouble in my case. Mailchimp api needs for some reason an array and I am not able to pass it via your Wrapper.

Do you have any recommendations?

Cannot reliably make multiple calls with one instance of the wrapper

First off, fantastic work! Thanks for writing this much needed wrapper. A+

I'm trying to use this wrapper to get a list of interest categories so then I can set them on the user update, but it looks like the wrapper retains the fields param for the second call and throws an error.

Is there a reset method or a recommended way to handle this without a second instantiation of the wrapper?

    $service = new Mailchimp\Mailchimp($api_key);

    $all_interests = $service->get("lists/$list_id/interest-categories/$interest_category_id/interests", array(
      'fields' => 'interests.id,interests.name'
    ));

    //some logic to figure out what interests for user

    $updated_user = $service->patch("lists/$list_id/members/$user_id", array(
      'merge_fields' => array(
        'FNAME' => $first_name,
        'LNAME' => $last_name
      ),
     'interests' = $user_interests

    ));

throws error

Error on line 162

Message: {"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Requested Fields Invalid","status":422,"detail":"Some of the fields requested were invalid: interests.id,interests.name","instance":""}

File: /vagrant/intranet/application/vendor/pacely/mailchimp-apiv3/src/Mailchimp.php

Collection collapse() method throwing an error : array_merge(): Argument #2 is not an array

Hello,

When calling the /lists/{list_id} resource using the GET method, I'm getting this error :

array_merge(): Argument #2 is not an array

Line 79, the collapse() method is throwing that error :

return $method == 'get' ? $collection->collapse() : $collection;

When I'm just returning $collection, it's working. I'm not sure how to fix that?

Thanks for making that library, very helpful! :)

Pagination does not work on Campaigns

Hi,
I'm starting to use your package, and the first thing I noticed was that Campaigns (I've yet to try with lists) don't care if I use pagination.

My call looks like this:

$res = $mc->get('/campaigns/',array(
    'fields' => 'campaigns.id,campaigns.name',
    'offset' => 10,
    'count' => 20
));

But it always return the firts 10 elements.

Am I doing something wrong?
The same operations work perfectly with subscribers management.

TIA,
Riccardo

Getting error while doing composer install

Hi Chris,
I have added
"require": {
"pacely/mailchimp-apiv3": "dev-master"
}

to composer.json as
{
"name": "pacely/mailchimp-apiv3",
"description": "Simple API wrapper for Mailchimp API V3",
"version": "0.1",
"type": "library",
"keywords": ["mailchimp", "api", "php", "v3"],
"license": "MIT",
"authors": [
{
"name": "Chris Magnussen",
"email": "[email protected]"
}
],
"autoload": {
"psr-4": {
"Mailchimp": "src/"
}
},
"require": {
"php": ">=5.4.0",
"guzzlehttp/guzzle": "~5.0",
"illuminate/support": "~5.0"
},
"require-dev": {
"phpspec/phpspec": "~2.2"
},
"minimum-stability": "dev",

"require": {
    "pacely/mailchimp-apiv3": "dev-master"
}

}

When I try to do
php composer.phar update, it shows an error saying 'The requested package pacely/mailchimp-apiv3 0.1 could not be found.'

Could you please inform what could have gone wrong?
Thanks
error

Expose ClientException to api callers

The following code in makeRequest will discard the error information in a call

  private function makeRequest($resource, $arguments, $method)
    {
        try {
            $options = $this->getOptions($method, $arguments);
            $response = $this->client->{$method}($this->endpoint . $resource, $options);

            $collection = new Collection(
                json_decode($response->getBody())
            );

            if ($collection->count() == 1) {
                return $collection->collapse();
            }

            return $collection;
        } catch (ClientException $e) {
            throw new Exception($e->getResponse()->getBody());
        } catch (RequestException $e) {
            $response = $e->getResponse();

            if ($response instanceof ResponseInterface) {
                throw new Exception($e->getResponse()->getBody());
            }

            throw new Exception($e->getMessage());
        }
    }

Since you discard the info that ClientException contains we cannot see what kind of Error mailchimp throws. For instance we need to create a customer if it does not exist, which we need to check if the response status is 404.

The PUT method is not enough here since it will throw if the email has changed.

Is it possible to expose the raw ClientException here instead of discarding it (i.e. throw $e) or what is the reasoning about doing this?

Reusing the Mailchimp object throws a Bad Request error

This works:

$this->mc = new \Mailchimp\Mailchimp($this->apiKey);
$lists = $this->mc->request('lists',array(
        'count' => 100,
        'fields'=>'lists.id,lists.name'
    ),'GET');
var_dump($lists);

$this->mc = new \Mailchimp\Mailchimp($this->apiKey);
$lists2 = $this->mc->request('lists',array(
        'count' => 100,
        'fields'=>'lists.id,lists.name'
    ),'GET');
var_dump($lists2);

Re-initializing the Mailchimp object for each call doesn't seem like it should be necessary, though? This fails:

$lists = $this->mc->request('lists',array(
        'count' => 100,
        'fields'=>'lists.id,lists.name'
    ),'GET');
var_dump($lists);

$lists2 = $this->mc->request('lists',array(
        'count' => 100,
        'fields'=>'lists.id,lists.name'
    ),'GET');
var_dump($lists2);

Here's the exception thrown:

Fatal error:  Uncaught exception 'Exception' with message '<HTML><HEAD>
<TITLE>Bad Request</TITLE>
</HEAD><BODY>
<H1>Bad Request</H1>
Your browser sent a request that this server could not understand.<P>
Reference&#32;&#35;7&#46;116c1160&#46;1436314067&#46;0
</BODY>
</HTML>

Batches

Hello!

I'm not sure if I'm just being an idiot, but I can't get batches to work. Any idea why this code would always return an error 400, 'Schema describes object, array found instead'?

    public function update(Request $request) {

        $orders         = $request->orders;
        $list           = $request->list;

        $operations = [];

        foreach($orders as $order) {

            $data       = [
                'email_address'     => $order['email'],
                'status'            => 'Subscribed'
            ];

            $operations[] = [
                'method'    => 'POST',
                'path'      => 'lists/' . $list . '/members',
                'body'      => json_encode($data)
            ];
        }

        $response   = $this->mc->request('batches', [
            $operations
        ], 'post');

        return Response::json([
            'message'   => $response
        ], 200);

    }

PHP >= 5.5.0 required is incorrect

Unless there's something that I've overlooked, the requirements for mailchimp-api-v3 are listed as follows:

"require": {
"php": ">=5.5.0",
"guzzlehttp/guzzle": "~5.0|~6.0",
"illuminate/support": "~5.0"
},

While the requirements for "illuminate/support" are as follows:

"require": {
"php": ">=5.6.4",
"ext-mbstring": "",
"doctrine/inflector": "~1.1",
"illuminate/contracts": "5.4.
",
"paragonie/random_compat": "~1.4|~2.0"
},

So clearly php >= 5.6.4 is required. I changed the "illuminate/support" version to "5.2.x-dev" for it to work in PHP 5.5.9.

POST Request

Hi @ChrisRM,

Thanks for putting this together - very handy.

I'm trying to run a POST request, but seems I cannot get my arguments right. The GET request works fine:

$lists = $mc->request('lists/{list_id}/members', [
    'fields' => 'members.email_address,members.status',
    'count' => 30
]);

How would it look at as a POST request. I want to subscribe an email programmatically. Thanks very much!

Laravel Version Support

Does this package only work on Laravel version 5.x? Wasn't quite sure from the documentation.

Thanks

Are the examples correct?

Hi,

I was just looking for examples to do filtering in lists and I spotted this repo in GitHub, thanks for the contribution.
I'm not using this code, but something else, however this example doesn't seem correct:

$result = $mc->post('lists', [
    'name' => 'New list',
    'permission_reminder' => 'You signed up for updates on Greeks economy.',
    'email_type_option' => false,
    'contact' => [
        'company' => 'Doe Ltd.',
        'address1' => 'DoeStreet 1',
        'address2' => '',
        'city' => 'Doesy',
        'state' => 'Doedoe',
        'zip' => '1672-12',
        'country' => 'US',
        'phone' => '55533344412'
    ],
    'campaign_defaults' => [
        'from_name' => 'John Doe',
        'from_email' => '[email protected]',
        'subject' => 'My new campaign!',
        'language' => 'US'
    ]
]);

From what I understand you also need to set visibility 'prv' or 'pub' and set use_archive_bar true or false.

Error initiating: Call to undefined method Mailchimp\MailchimpFacade::request()

Hi
I'm having trouble initiating this package correctly in laravel 5.1. Probably a PICNIC error but need some help!

I've installed the package, added the service provider and facade per the docs. I've published the config file and added my apikey.

However trying the sample code for a simple request of lists I'm coming up with this error:

Call to undefined method Mailchimp\MailchimpFacade::request()

Here's my code:

$mc = new MC;

    $result = $mc->request( 'lists' , [
        'fields' => 'lists.id,lists.name,lists.stats.member_count' ,
        'offset' => 0 ,
        'count' => 10
    ] );

    ddd($result);

If I try and initiate mailchimp direct I am able to get the list as expected but that appears to be bypassing the package and I'd rather use the facade and not have to worry about pulling the apikey etc.

This works:

$mc = new \Mailchimp\Mailchimp('xxxxx xxxxx');

    $result = $mc->request( 'lists' , [
        'fields' => 'lists.id,lists.name,lists.stats.member_count' ,
        'offset' => 0 ,
        'count' => 10
    ] );

What am I doing wrong? How can I use the facade correctly?

Thanks

Wrong examples

This examples are misleading, i'm trying to use it as you explain:

	public function suscribe(Request $request) {
		$result = $MC::request('lists', [
				'fields' => 'lists.id,lists.name,lists.stats.member_count',
				'offset' => 10,
				'count' => 10
		]);
	}

Also tried with $mc->request() with no success. How it is supossed to be used?, and please don't tell me to go to the documentation, i'm coming from there.

Get the last subscribers in a day

I need to know how I can make a request to the APi to meet the last subscribers. This request will be made every hour if is possible

SSL issue

Hi guys, I'm trying to get this wrapper running on my local dev box but when trying your example code from the readme I'm seeing the following error:

Exception in Mailchimp.php line 170:
cURL error 60: SSL certificate problem: unable to get local issuer certificate (see http://curl.haxx.se/libcurl/c/libcurl-errors.html)

Is there any way I can enforce non-ssl or is this a requirement from Mailchimp? Thanks

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.