PHP - Newsletter API (CampaignCreate)

Hi all,

I am signed up to a newsletter management provider called “MyNewsletterBuilder” and they have provided me with an API key to connect to their system and manage my newsletters. Using this API, I should be able to create new newsletters but I am having a little difficulty getting it to work and hope that perhaps a more experienced developer would be able to help me out.

Here is the wrapper they have provided:

<?php
/**
 * Copyright JBA Network, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * See http://www.mynewsletterbuilder.com/api/
 * $Id: MnbApi.class.php 67103 2011-07-17 14:02:55Z mnb-admin $
 */

// =(
define('_MNB_MAGIC_QUOTES', ini_get("magic_quotes_runtime"));

class MnbApi
{
	public $version = '1.0';
	public $build   = '$Rev: 67103 $';
	public $errno   = '';
	public $errstr  = '';

	/**
	 * The API Key used to validate the request
	 */
	protected $api_key = 'BLANKED OUT FOR SECURITY';

	/**
	 * API Host URL target
	 */
	protected $api_host = 'api.mynewsletterbuilder.com';

	/**
	 * Server request timeout [300]
	 */
	protected $timeout = 300;

	/**
	 * Use a secure connection (SSL/TLS) [FALSE]
	 */
	protected $secure = FALSE;

	/**
	 * Error codes
	 */
	public static $E_CONNECT = 1;
	public static $E_RESPONSE = 2;
	public static $E_TIMEOUT = 3;
	public static $E_UNKNOWN = 4;

	/**
	 * __construct()
	 * @param string $api_key An API Key to authenticate the request with.
	 * @param boolean $secure Optional, force secure connection
	 */
	public function __construct($api_key, $secure = FALSE)
	{
		$this->api_key = $api_key;
		$this->secure = (bool)$secure;
	}

	public function __destruct() {}

	public function SetTimeout($secs = 300)
	{
		$secs = (int)$secs;

		if ($secs > 0)
			$this->timeout = $secs;

		return TRUE;
	}

	public function GetTimeout()
	{
		return $this->timeout;
	}

	public function hasError()
	{
		return !empty($this->errno);
	}

	public function getErrorCode()
	{
		return $this->errno;
	}

	public function getErrorMessage()
	{
		return $this->errstr;
	}

	public function UseSecure($secure = TRUE)
	{
		if ($secure === TRUE)
			$this->secure = TRUE;
		else
			$this->secure = FALSE;
	}

    public function Campaigns($filters = array())
    {
		$params = array(
			'filters' => $filters
		);

		return $this->Execute('Campaigns', $params);
	}

	public function CampaignDetails($id)
	{
		$params = array(
			'id' => $id
		);

		return $this->Execute('CampaignDetails', $params);
	}

	public function CampaignCreate($name, $subject, $from, $reply, $html, $text = '', $link_tracking = TRUE, $gat = FALSE)
	{
		$params = array(
			'name' => $name,
			'subject' => $subject,
			'from' => $from,
			'reply' => $reply,
			'html' => $html,
			'text' => $text,
			'link_tracking' => $link_tracking,
			'gat' => $gat
		);

		return $this->Execute('CampaignCreate', $params);
	}

	public function CampaignUpdate($id, $details)
	{
		$params = array(
			'id' => $id,
			'details' => $details
		);

		return $this->Execute('CampaignUpdate', $params);
	}

	public function CampaignCopy($id, $name)
	{
		$params = array(
			'id' => $id,
			'name' => $name
		);

		return $this->Execute('CampaignCopy', $params);
	}

	public function CampaignDelete($id)
	{
		$params = array(
			'id' => $id
		);

		return $this->Execute('CampaignDelete', $params);
	}

	public function CampaignSchedule($id, $when, $lists, $smart = FALSE, $confirmed = FALSE)
	{
		$params = array(
			'id' => $id,
			'when' => $when,
			'lists' => $lists,
			'smart' => $smart,
			'confirmed' => $confirmed
		);

		return $this->Execute('CampaignSchedule', $params);
	}

	public function CampaignStats($id)
	{
		$params = array(
			'id' => $id
		);

		return $this->Execute('CampaignStats', $params);
	}

	public function CampaignRecipients($id, $page = 0, $limit = 1000)
	{
		$params = array(
			'id' => $id,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('CampaignRecipients', $params);
	}

	public function CampaignOpens($id, $page = 0, $limit = 1000)
	{
		$params = array(
			'id' => $id,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('CampaignOpens', $params);
	}

	public function CampaignSubscribes($id, $page = 0, $limit = 1000)
	{
		$params = array(
			'id' => $id,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('CampaignSubscribes', $params);
	}

	public function CampaignUnsubscribes($id, $page = 0, $limit = 1000)
	{
		$params = array(
			'id' => $id,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('CampaignUnsubscribes', $params);
	}

	public function CampaignBounces($id, $page = 0, $limit = 1000)
	{
		$params = array(
			'id' => $id,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('CampaignBounces', $params);
	}

	public function CampaignUrls($id)
	{
		$params = array(
			'id' => $id
		);

		return $this->Execute('CampaignUrls', $params);
	}

	public function CampaignClicks($id, $page = 0, $limit = 1000)
	{
		$params = array(
			'id' => $id,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('CampaignClicks', $params);
	}

	public function CampaignClickDetails($id, $url_id = 0, $page = 0, $limit = 1000)
	{
		$params = array(
			'id' => $id,
			'url_id' => $url_id,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('CampaignClickDetails', $params);
	}

	public function Lists()
	{
		return $this->Execute('Lists', array());
	}

	public function ListDetails($id)
	{
		$params = array(
			'id' => $id
		);

		return $this->Execute('ListDetails', $params);
	}

	public function ListCreate($name, $description = '', $visible = FALSE, $default = FALSE)
	{
		$params = array(
			'name' => $name,
			'description' => $description,
			'visible' => $visible,
			'default' => $default
		);

		return $this->Execute('ListCreate', $params);
	}

	public function ListUpdate($id, $name = '', $deails)
	{
		$params = array(
			'id' => $id,
			'details' => $details
		);

		return $this->Execute('ListUpdate', $params);
	}

	public function ListDelete($id, $delete_subs = FALSE)
	{
		$params = array(
			'id' => $id,
			'delete_subs' => $delete_subs
		);

		return $this->Execute('ListDelete', $params);
	}

	public function Subscribers($statuses, $lists, $page = 0, $limit = 1000)
	{
		$params = array(
			'statuses' => $statuses,
			'lists' => $lists,
			'page' => $page,
			'limit' => $limit
		);

		return $this->Execute('Subscribers', $params);
	}

	public function SubscriberDetails($id_or_email)
	{
		$params = array(
			'id_or_email' => $id_or_email
		);

		return $this->Execute('SubscriberDetails', $params);
	}

	public function SubscriberUpdate($id_or_email, $details, $lists)
	{
		$params = array(
			'id_or_email' => $id_or_email,
			'details' => $details,
			'lists' => $lists
		);

		return $this->Execute('SubscriberUpdate', $params);
	}

	public function Subscribe($details, $lists, $skip_opt_in = FALSE, $update_existing = TRUE)
	{
		$params = array(
			'details' => $details,
			'lists' => $lists,
			'skip_opt_in' => $skip_opt_in,
			'update_existing' => $update_existing
		);

		return $this->Execute('Subscribe', $params);
	}

	public function SubscribeBatch($subscribers, $lists, $skip_opt_in = FALSE, $update_existing = TRUE)
	{
		$params = array(
			'subscribers' => $subscribers,
			'lists' => $lists,
			'skip_opt_in' => $skip_opt_in,
			'update_existing' => $update_existing
		);

		return $this->Execute('SubscribeBatch', $params);
	}

	public function SubscriberUnsubscribe($id_or_email)
	{
		$params = array(
			'id_or_email' => $id_or_email
		);

		return $this->Execute('SubscriberUnsubscribe', $params);
	}

	public function SubscriberUnsubscribeBatch($ids_or_emails)
	{
		$params = array(
			'ids_or_emails' => $ids_or_emails
		);

		return $this->Execute('SubscriberUnsubscribeBatch', $params);
	}

	public function SubscriberDelete($id_or_email)
	{
		$params = array(
			'id_or_email' => $id_or_email
		);

		return $this->Execute('SubscriberDelete', $params);
	}

	public function SubscriberDeleteBatch($ids_or_emails)
	{
		$params = array(
			'ids_or_emails' => $ids_or_emails
		);

		return $this->Execute('SubscriberDeleteBatch', $params);
	}

	public function AccountDetails()
	{
		$params = array();

		return $this->Execute('AccountDetails', $params);
	}

	public function AccountKeys($username, $password, $disabled = FALSE)
	{
		$params = array(
			'username' => $username,
			'password' => $password,
			'disabled' => $disabled
		);

		return $this->Execute('AccountKeys', $params);
	}

	public function AccountKeyCreate($username, $password)
	{
		$params = array(
			'username' => $username,
			'password' => $password
		);

		return $this->Execute('AccountKeyCreate', $params);
	}

	public function AccountKeyEnable($username, $password, $id_or_key)
	{
		$params = array(
			'username' => $username,
			'password' => $password,
			'id_or_key' => $id_or_key
		);

		return $this->Execute('AccountKeyEnable', $params);
	}

	public function AccountKeyDisable($username, $password, $id_or_key)
	{
		$params = array(
			'username' => $username,
			'password' => $password,
			'id_or_key' => $id_or_key
		);

		return $this->Execute('AccountKeyDisable', $params);
	}

	/**
	 * Test server response
	 * @param string String to echo
	 * @return string
	 */
	public function HelloWorld($val = "Hello, World!")
	{
		$params = array('val' => $val);

		return $this->Execute('HelloWorld', $params);
	}

	/**
	 * Connect to remote server and handle response.
	 * @param string $method Action to invoke
	 * @param mixed $params Parameters required for $method
	 * @return mixed Server response, FALSE on error.
	 */
	protected function Execute($method, $params = array())
	{
		$this->errno = '';
		$this->errstr = '';
		$params['api_key'] = $this->api_key;
		$query_data = http_build_query($params);

		$request = "POST /" . $this->version . "/" . $method . "/php HTTP/1.1\\r\
"
				 . "Host: " . $this->api_host . "\\r\
"
				 . "User-Agent: MNB_API PHP " . $this->version . "/" . $this->build . "\\r\
"
				 . "Content-type: application/x-www-form-urlencoded; charset=\\"utf-8\\"\\r\
"
				 . "Content-length: " . strlen($query_data) . "\\r\
"
				 . "Connection: close\\r\
\\r\
"
				 . $query_data;

		if ($this->secure)
			$sp = fsockopen('ssl://' . $this->api_host, 443, $errno, $errstr, 30);
		else
			$sp = fsockopen($this->api_host, 80, $errno, $errstr, 30);

		if (!$sp)
		{
			$this->errno = self::$E_CONNECT;
			$this->errstr = "Failed connecting. Error: $errno, $errstr";

			return FALSE;
		}

		stream_set_timeout($sp, $this->timeout);
		fwrite($sp, $request);

		$response = '';

		while (!feof($sp))
			$response .= fread($sp, 8192);

		$meta = stream_get_meta_data($sp);

		if ($meta['timed_out'])
		{
			$this->errno = self::$E_TIMEOUT;
			$this->errstr = "The socket timed out. Try a larger timeout? (current: $this->timeout)";

			return FALSE;
		}

		if (_MNB_MAGIC_QUOTES)
			$response = stripslashes($response);

		$response = explode("\\r\
\\r\
", $response, 2);
		$data = unserialize($response[1]);

		if ($data === FALSE)
		{
			$data = array(
				'errno' => self::$E_RESPONSE,
				'errstr' => 'Unexpected response, received: ' . $response[1]
			);
		}

		// An error from the server will match this format.
		if (is_array($data) && isset($data['errstr']))
		{
			$this->errno = $data['errno'];
			$this->errstr = $data['errstr'];

			return FALSE;
		}

		return $data;
	}
}

The method I’m told I should be using is their “CampaignCreate” function. The documentation for this function can be found here -> http://www.mynewsletterbuilder.com/api/docs/1.0/CampaignCreate

I have uploaded the wrapper (MnbApi.class.php) to my server and referenced it in my script to create the campaign. Here is that script:

<?php

require_once('MnbApi.class.php');

$api = new MnbApi($api_key);

if ($html = $content) {
	$result = $api->CampaignCreate($name, $subject, $from, $reply, $html, $text, $link_tracking, $gat);
		$name = 'Aries Daily Newsletter ('. $todayuk .'';
		$subject = 'Your Daily Horoscope';
		$from = $email;
		$reply = $email;
		$html = $content;
		$text = '';
		$email['name'] = 'I\\'ve Got Kids';
		$email['email'] = 'noreply@ivegotkids.com';
		$content = file_get_contents('http://ivegotkids.com/newsletters/aries-daily.php');
		$todayuk = date('d M Y');
 if(true !== $result){
        throw new Exception($api->errstr, $api->errno);
    }
}

No errors are produced when I run the above script. However, when I log in to my MNB account, no new newsletters appear either.

Would somebody be so kind as to take a look over the wrapper, documentation & my script and perhaps correct me on what I have misinterpreted.

Thanks in advance.

The only thing i see wrong is your variables are been declared after you make the call to the API, simply move the API call to after your variables have been declared and it should work fine.

Thanks Chris.

Changing the script around so the variables were declared has worked so far as it now does create the newsletter as expected… now can you see anywhere there how I am able to return the ID of the newly created newsletter?

Regards,

Your variable $result stores the id from the API call so simply returning it will hold the value.

Hi Chris,

Thanks again for the help. I managed to get the ID of the generated newsletter by returning the result as you suggested. There is 1 last step to completing this newsletter schedule that I need assistance with.

The API Documentation states that I can schedule a campaign for automatic delivery. I have set everything the way I believe it needs to be set but it’s not scheduling it. It’s creating the newsletter but it’s just sitting there as a draft waiting to be sent manually.

Here is my code:

<?php 

// Setting up the connection:
		require_once('MnbApi.class.php');
		$api = new MnbApi('xxxxxxxxxxxxxxxxxxxx');

// Declaring Variables:
		$content = file_get_contents('http://ivegotkids.com/newsletters/aries-daily.php');
		$todayuk = date('d M Y');
		$email['name'] = 'I\\'ve Got Kids';
		$email['email'] = 'noreply@ivegotkids.com';
		$name = 'Aries Daily Newsletter ('. $todayuk .')';
		$subject = 'Your Daily Horoscope';
		$from = $email;
		$reply = $email;
		$html = $content;
		$text = '';
		$link_tracking = TRUE;
		$gat = TRUE;

// Creating the Newsletter:
		if ($html = $content) {
		$result = $api->CampaignCreate($name, $subject, $from, $reply, $html, $text, $link_tracking, $gat);

// 		if(true !== $result){
//        throw new Exception($api->errstr, $api->errno); } }
	}	
		
	$id = $result;

	echo 'Your newsletter has been generated and sent - ID Number: '. $id .'';
	
// Now we schedule the newsletter to be sent today to everybody on the "Aries" mailing list.
		date_default_timezone_set('EST');
		$now = date('Y-m-d H:i:s');
		$when = $now;
		$lists = '261637';
		$smart = TRUE;
		$confirmed = FALSE;
		
	if (isset($id)) {
	$sendmail = $api->CampaignSchedule($id,$when,$lists,$smart,$confirmed);
	}
	
	$confirm = $sendmail;

	echo ($confirm);
	?> 
 
	
	

As you can see - I have set the $when and the $lists variables with the current date and the ID of the list I want to set the mail to. I have also tried setting the timezone to EST as this is where their server is located - I have tried it without this set also.

Unfortunately, I cannot see from their documentation any working examples of the CampaignSchedule function - only instructions on what param’s to pass to it. I’m hoping you or maybe someone else reading this post will have experience in doing this and point me in the right direction.

This is all the instructions they provide: http://www.mynewsletterbuilder.com/api/docs/1.0/CampaignSchedule

Regards,
Chris

I had a look at the docs and from what i can see everything is correct apart from the $lists variable which is a string not an array, I’m just taking a wild guess but from what i can see this is what it needs to be based on your string.

$lists = array(2, 6, 16, 37);

That is strange because it says it should be the list ID’s of all the “lists” I want to send the newsletter to. Lists are stored as categories in my account and the only category I want it to send to has an ID of 261637.

Where did you get the info from to break up the ID into 4 separate ones? And how will I derive that for myself in future mailings?

Or would I just use $list = array(‘261637’); instead?

The documentation states an array of list id’s – “An array of list ids to send the delivery to.”

I made an assumption because it looked like a pattern.

That would be right if the list id is 261637

Hiya,

I tried that and it still didn’t work. I am going to have to come to the conclusion there is either something wrong with their API or something wrong in the documentation because I honestly cannot see what could be wrong with the code.

Again, this is the code as it looks now:

<?php 

// Setting up the connection:
		require_once('MnbApi.class.php');
		$api = new MnbApi('xxxxxxxxxxxxxxxxxxx');

// Declaring Variables:
		$content = file_get_contents('http://ivegotkids.com/newsletters/aries-daily.php');
		$todayuk = date('d M Y');
		$email['name'] = 'I\\'ve Got Kids';
		$email['email'] = 'noreply@ivegotkids.com';
		$name = 'Aries Daily Newsletter ('. $todayuk .')';
		$subject = 'Your Daily Horoscope';
		$from = $email;
		$reply = $email;
		$html = $content;
		$text = '';
		$link_tracking = TRUE;
		$gat = TRUE;

// Creating the Newsletter:
		if ($html = $content) {
		$result = $api->CampaignCreate($name, $subject, $from, $reply, $html, $text, $link_tracking, $gat);

	}	
		
	$id = $result;


	
// Now we schedule the newsletter to be sent today to everybody on the "Aries" mailing list.
		$now = date('Y-m-d H:i:s');
		$when = $now;
		$lists = array(261637);
		$smart = TRUE;
		$confirmed = FALSE;
		
	if (isset($id)) {
	$sendmail = $api->CampaignSchedule($id,$when,$lists,$smart,$confirmed);
	}
	
	$confirm = $sendmail;
	

// Now we display the confirmation messages.	
	?> 
	<?php echo 'Your newsletter has been generated - ID Number: '. $id .''; ?>
    <br /> 
	<?php echo 'The current date/time is '. $now .''; ?>
	<br />
    <?php echo ($confirm); ?>

It produces the newsletter as expected
It gives me the ID as expected
It does NOT schedule it for delivery

I have sent an email to them asking them if there is a problem with it.

In the meantime, if you (or anyone else) can spot anything I might be able to try in case they come back and say everything is fine… I’d be appreciative. I’ve spent days on this now and it’s beginning to get me a little anxious.

Sorry for the delay bud, without access to an API key i wouldn’t know how to continue with this as i read through the documentation at least 10 times and can’t fault your code in any way.