maksimerohin
2/11/2019 - 11:41 AM

Add Subscriber to MailChimp

Добавляет подписчика в список MailChimp.

document.addEventListener('wpcf7mailsent', function (event) {
  var inputs = event.detail.inputs;

  for (var i = 0; i < inputs.length; i++) {
    if ('your-name' == inputs[i].name) {
      yourName = inputs[i].value;
    }
    if ('email' == inputs[i].name) {
      yourEmail = inputs[i].value;
    }
  }

  console.log('yourName: ' + yourName);
  console.log('yourEmail: ' + yourEmail);

  // Подписываем в MailChimp
  $.ajax({
    cache: false,
    timeout: 8000,
    url: '/wp-admin/admin-ajax.php',
    type: "POST",
    data: ({ action: 'vakio_order_sent', list: '1c001c1824', name: yourName, email: yourEmail }),

    beforeSend: function () {
    },

    success: function (data, textStatus, jqXHR) {
    },

    error: function (jqXHR, textStatus, errorThrown) {
    },

    complete: function (jqXHR, textStatus) {
    }
  });
}
function subscribe_order() {
	$listId = $_POST['list'];
	$name = $_POST['name'];
	$email = $_POST['email'];

	$data = [
		'listId'     => $listId,
		'email'     => $email,
		'status'    => 'subscribed',
		'firstname' => $name
	];
	
	syncMailchimp($data);
}
add_action( 'wp_ajax_vakio_order_sent', 'subscribe_order' );
add_action( 'wp_ajax_nopriv_vakio_order_sent', 'subscribe_order' );

function syncMailchimp($data) {
	$apiKey = 'b7f2a20246d505aad732141763a3834a-us17';
	$listId = $data['listId'];

	$memberId = md5(strtolower($data['email']));
	$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
	$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;

	$json = json_encode([
    'email_address' => $data['email'],
    'status'        => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
    'merge_fields'  => [
        'FNAME'     => $data['firstname']
    ]
	]);

	$ch = curl_init($url);

	curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
	curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_TIMEOUT, 10);
	curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                                                                                                                 

	$result = curl_exec($ch);
	$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
	curl_close($ch);

	echo $httpCode;
	exit;
	return $httpCode;
}