Mailchimp API - пакетная загрузка - PullRequest
0 голосов
/ 02 июля 2019

Я пытаюсь импортировать список из 879 пользователей (в пакетном режиме) в список Mailchimp.Библиотека, которую я использую: https://github.com/pacely/mailchimp-api-v3.

Я создал консольную команду Laravel для этого.Код:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Mailchimp\Mailchimp;
use Exception;

class ImportContactsIntoMailchimp extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'mailchimp:import:contacts';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Import contacts into mailchimp.';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * If an e-mail address starts with this, mailchimp won't allow it
     * http://kb.mailchimp.com/lists/growth/limits-on-role-based-addresses
     *
     * @var array
     */
    private $nomail = array(            
        'abuse@',
        'admin@',
        'billing@',
        'compliance@',
        'devnull@',
        'dns@',
        'ftp@',
        'hostmaster@',
        'inoc@',
        'ispfeedback@',
        'ispsupport@',
        'list-request@',
        'list@',
        'maildaemon@',
        'noc@',
        'no-reply@',
        'noreply@',
        'null@',
        'phish@',
        'phishing@',
        'postmaster@',
        'privacy@',
        'registrar@',
        'root@',
        'security@',
        'spam@',
        'support@',
        'sysadmin@',
        'tech@',
        'undisclosed-recipients@',
        'unsubscribe@',
        'usenet@',
        'uucp@',
        'webmaster@',
        'www@'
    );

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $result = DB::table('contacts_billonline')
            ->select(
                'email',
                'firstname',
                'surname',
                'phone'
            )
            ->get();

        $batch_count = 250;                                 
        $email_column = 'email'; 
        $merge_columns = array(                             
            'EMAIL'     => 'email',
            'FNAME'     => 'firstname',
            'LNAME'     => 'surname',
            'PHONE'     => 'phone',
        );
        $listId = $this->ask('What is the list id?'); 

        // Create our mailchimp connection
        $mailchimp_key = config('mailchimp.apikey');
        $mc = new Mailchimp($mailchimp_key);
        $contact_list = '/lists/'.$listId.'/members';

        $total = count($result);

        for ($i = 0; $i < $total; $i += $batch_count)
        {
            $batch = array();
            for ($j = 0; $j < $batch_count; $j++)
            {
                $row_number = $i + $j;

                if ($row_number === $total)
                {
                    // If we reached the end of the list, stop trying to add operations
                    break;
                }

                // Get the email address from the result for this row
                $email = &$result[$row_number]->{$email_column};


                // Is this a valid email address? If so add it to the batch
                if ($this->isValidEmail($email)) {

                    $this->info($email);

                    // Get our merge columns for this row and put them in the array
                    $merge_fields = array();
                    foreach ($merge_columns as $key => &$column) {
                        $merge_fields[$key] = &$result[$row_number]->{$column};
                    }

                    $insert_email = array(
                        'email_address' => $email,
                        'status'        => 'subscribed',
                        'merge_fields'  => $merge_fields,
                        'tags' => ['Contacts']
                    );

                    $batch_operation = array(
                        'method'        => 'POST',
                        'path'          => $contact_list,
                        'body'          => json_encode($insert_email)
                    );

                    $batch[] = $batch_operation;
                }
            }

            $body = array();
            $body['operations'] = $batch;
            $batch_result = $mc->post('/batches', $body);

            $this->info($batch_result);
        }
    }


    /**
     * Is this is an email address mailchimp would see as valid?
     *
     * @param $email
     * @return bool
     */
    function IsValidEmail(&$email)
    {
        foreach ($this->nomail as &$bad_mail)
        {
            if (strpos($email, $bad_mail) === 0)
            {
                return false;
            }
        }

        $validator = Validator::make(
            array(
                'email' => &$email
            ),
            array(
                'email' => 'required|email'
            )
        );

        if ($validator->fails())
        {
            return false;
        }

        return true;
    }

}

Я пытаюсь импортировать пользователей из таблицы базы данных в пакетном режиме в Mailchimp.

Ключ API установлен правильно.Я также пытаюсь установить тег «Контакты» для подписчиков.

Идентификатор списка также установлен правильно.

Проблема в том, что список не импортирован.Результат в терминале:

{"id": "c48cd17f6d", "status": "pending", "total_operations": 0, "done_operations": 0, "errored_operations": 0,"submitted_at": "2019-07-02T10: 58: 22 + 00: 00", "completed_at": "", "response_body_url": "", "_ ссылки": [{ "отн": "родитель", "HREF":" https://us8.api.mailchimp.com/3.0/batches","method":"GET","targetSchema":"https://us8.api.mailchimp.com/schema/3.0/Definitions/Batches/CollectionResponse.json","schema":"https://us8.api.mailchimp.com/schema/3.0/CollectionLinks/Batches.json"},{"rel":"self","href":"https://us8.api.mailchimp.com/3.0/batches/c48cd17f6d","method":"GET","targetSchema":"https://us8.api.mailchimp.com/schema/3.0/Definitions/Batches/Response.json"},{"rel":"delete","href":"https://us8.api.mailchimp.com/3.0/batches/c48cd17f6d","method":"DELETE"}]}

Что я делаю не так?

...