Mailchimp for WP add subscriber programmatically - php

i am trying to add an user to a MailChimp list programmatically (so he is a subscriber of any emails i will send).
I do have the pro-version of the MailChimp for WordPress plugin.
Is there a way to add - and remove a user (Email and three fields) to a list dynamically?
There seems to be an API (http://developer.mc4wp.com/), but i did not found a function to do so.
Is there one?

Use the mc4wp_get_api function to grab an instance of the MailChimp for WordPress API. Then call the subscribe() function add an email to a list:
$list_id = "2341ca4321";
$email = "subscriber#email.com";
$api = mc4wp_get_api();
$api->subscribe($list_id, $email);
The subscribe() function returns a boolean. This return value simply reports if the subscribe request succeeded. Will return false if the user is already on the list
$list_id can be found when logged into MailChimp, looking under a list, Settings > List name and campaign defaults > List ID

include('/MailChimp.php');
$MailChimp = new \DrewM\MailChimp\MailChimp("API-KEY");
$result = $MailChimp->get('lists');
$list_id = 'a0123a45f'; // List Key
$result = $MailChimp->post("lists/$list_id/members", [
'email_address' => test#test.com,
'status' => 'subscribed',
'merge_fields' => array('FNAME'=>'test', 'LNAME'=>'tester'),
]);

Related

What is the best option to send emails in laravel with different email template

We are currently using laravel Event listener to send emails for laravel. Basically this is a slot booking option, so sometimes we have to send emails to sender and sometimes we have to send to receiver and sometimes we have to send emails other partners of the slots. In the current case we are using a single Event Listner to send different emails fir the different actions users taking on the slot like cancel meeting, add one more member etc. But generally in the case the email templates would be different only the dunamic variables we need to change.
But in the new case we have to send 4 or 5 emails to different users with different email templates and different contents on a single action. If we plan this in a single event listner, how we can handle this?
$event_id=$event->user['XXXXX'];//event id
$slot_type=$event->user['XXXXX'];//slot type
$notification_type=$event->user['XXXXX']; //slot type
$scheduler_slot_info_ids=$event->user['XXXX'];
$data = $schedulerHelper->getOnetoOneNotificationContents($scheduler_slot_info_ids,$event_id,$slot_type);
$action_trigger_by=$event->user['XXXXX'];
//$data['subject'] = 'CARVRE SEVEN|MEETING CONFIRMED';
$data['subject'] = $event->user['XXXX'];
// $data['template'] = 'emailtemplates.scheduler.oneToOneMeetingConfirmed';
$data['template'] = $event->user['XXXX'];
$invitee_id=Crypt::encryptString($data['XXXX']);
$crypt_event_id=Crypt::encryptString($event_id);
$data['link'] = url('XXXX');
$data['email_admin'] = env('FROM_EMAIL');
$data['mail_from_name'] = env('MAIL_FROM_NAME');
// $data['receiver_email'] = 'XXXXXXX';//$invitee['email'];
//Calling mail helper function
MailHelper::sendMail($data);
Make either a table or hardcoded array with template renderers, then have those renderers render a twig/blade/php template based upon the variables you're supplying and all other variables you'd need for feeding into the mailer.
Then just loop through all your receiving candidates and render the appropriate emails with the correct renderer.
You'll have to make a few utility classes and all to accomplish this, but once you get it up and sorted it will be easy to manage and expand with more templates.
Just a rough outline of what I'd use
protected $renderers = [
'templateA' => '\Foo\Bar\BazEmailRender',
'templateB' => '\Foo\Bar\BbyEmailRender',
'templateC' => '\Foo\Bar\BcxEmailRender',
];
public function getTemplate($name)
{
if(array_key_exists($name, $this->renderers)) {
$clazz = $this->renderers[$name];
return new $clazz();
}
return null;
}
public function handleEmails($list, $action)
{
$mailer = $this->getMailer();
foreach($list as $receiver) {
if(($template = $this->getTemplate($receiver->getFormat()))) {
$template->setVars([
'action' => $action,
'action_name' => $action->getName(),
'action_time' => $action->created_at,
// etc...
]);
$mailer->send($receiver->email, $template->getSubject(), $template->getEmailBody());
}
}
}

How to add multiple contacts at a single call through Getresponse api

I am trying to add subscriber to list through Getresponse api for single contact subscription to list i have to call api like this
$getresponse = new GetResponse(api key);
$result = $getresponse->addContact(listid,
$lead['name'],
$lead['email']
);
Now i want to add multiple emails at a single call, i cant use foreach loop for each contact, is there a function or endpoint to add multiple emails at a single call?
Getresponse official API shows only one contact.
https://apidocs.getresponse.com/v3/resources/contacts#contacts.create
As of now, there is no API endpoints for import contacts as bulk (csv or JSON).
Yes, Bala is correct. There is no such API method for GetResponse to insert multiple contacts. However, please check the below API codes to insert single contact to GetResponse.
include('GetResponseAPI3.class.php');
$getresponse = new GetResponse('your-getresponse-token-here');
$var = $getresponse->addContact(array
(
'name' => 'FirstName LastName',
'email' => 'emailid#something.com',
'dayOfCycle' => 0,
'campaign' => array('campaignId' => 'Campaign-id'),
'ipAddress' => 'XXX.XXX.XX.XX'
)
);
var_dump($var);

Retrieve All User Lists using Aweber API

I am adding AWeber as an autoresponder in a web application. Using AWeber API, I am able to add a new subscriber to list with a known name which is in this case is firstlist:
$app = new MyApp();
$app->findSubscriber('whtever#aol.com');
$list = $app->findList('firstlist');
$subscriber = array(
'email' => 'someemail#gmail.com',
'name' => 'Name here'
);
$app->addSubscriber($subscriber, $list);
Function definition for findList() is:
function findList($listName) {
try {
$foundLists = $this->account->lists->find(array('name' => $listName));
return $foundLists[0];
}
catch(Exception $exc) {
print $exc;
}
}
As I am developing a public application, so I need to provide users an option to select from their available lists.
Please guide me how I can retrieve all the lists name.
You are returning $foundLists[0] so it will return single list. Try to return foundLists and check what it returns.
This may help you: https://labs.aweber.com/snippets/lists
In short, I pulled the lists by first finding the Aweber User Id so that I could use it in the URL https://api.aweber.com/1.0/accounts/<id>/lists
To find the User ID, I first got the account.
$this->aweber->getAccount($token['access'], $token['secret']);
Then, I retrieve the user's information.
$aweber_user = $this->aweber->loadFromUrl('https://api.aweber.com/1.0/accounts');
From that, I grabbed the user ID with...
$id = $aweber_user->data['entries'][0]['id'];
Once I had the user ID, I could then retrieve their lists with...
$lists = $this->aweber->loadFromUrl('https://api.aweber.com/1.0/accounts/'.$id.'/lists');
This example is more of a procedural approach, of course, I recommend utilizing classes.

How can i get campaign's web id when campaign is created using API in Mailchimp?

I am using API version 1.3 of mailchimp to create Campaign programmatically in PHP.
I am using MCAPI class method campaignCreate() to create campaign. Campaign is created successfully and it returns campaign id in response which is string.
But i need Web id (integer value of campaign id) so that I can use it to open that campaign using link on my website.
For example: lets say I want to redirect user to this link - https://us8.admin.mailchimp.com/campaigns/show?id=941117 and for that i need id value as 941117 when new campaign is created.For now i am getting it as string like 6ae9ikag when new campaign is created using mailchimp API
Please let me know if anyone knows how to get campaign web id (integer value) using Mailchimp API in PHP
Thanks
I found an answer so wanted to share here.Hope it helps someone
I get campaign id as a string when createCampaign() method of MCAPI class is used.
You need to use below code to get web id (integer value of campaign id)
$filters['campaign_id'] = $campaign_id; // string value of campaign id
$campaign = $api->campaigns($filters);
$web_id = $campaign['data'][0]['web_id'];
This worked for me.
Thanks
<?php
/**
This Example shows how to create a basic campaign via the MCAPI class.
**/
require_once 'inc/MCAPI.class.php';
require_once 'inc/config.inc.php'; //contains apikey
$api = new MCAPI($apikey);
$type = 'regular';
$opts['list_id'] = '5ceacbda08';
$opts['subject'] = 'Test Newsletter Mail';
$opts['from_email'] = 'guna#test.com';
$opts['from_name'] = 'guna';
$opts['tracking']=array('opens' => true, 'html_clicks' => true, 'text_clicks' => false);
$opts['authenticate'] = true;
$opts['analytics'] = array('google'=>'my_google_analytics_key');
$opts['title'] = 'Test Newsletter Title';
$content = array('html'=>'Hello html content message',
'text' => 'text text text *|UNSUB|*'
);
$retval = $api->campaignCreate($type, $opts, $content);
if ($api->errorCode){
echo "Unable to Create New Campaign!";
echo "\n\tCode=".$api->errorCode;
echo "\n\tMsg=".$api->errorMessage."\n";
} else {
echo "New Campaign ID:".$retval."\n";
}
$retval = $api->campaignSendNow($retval);
?>
The web_id is returned by mailchimp when a call is made to the creation end point.
$mcResponce = $mailchimp_api->campaigns->create(...);
$web_id = $mcResponce['web_id'];
See the documentation.

Add custom attribute in order email templates - Magento

I have created a 'Companyname' attribute which gets added up in my Customer's Account information and is a required field.
It gets filled up on registration, form and edit pages fine and gets displayed on Customer's Grid in the back-end too.
However I am not able to display the Company name in any of my order email templates.
I believe this is because there is neither any column called 'companyname' in my order tables nor do I have any custom variable which I can pass to order/invoice/shipment templates to display Company name right next to the line after Customer's name.
Can any one point out the file where I can create this custom variable containing my custom 'companyname' attribute and pass it to all types of sales email templates
Thanks
After a little bit of searching I found the right file to make the changes. Since I already had 'companyname' as one of my attributes I retrieved the value of this field and passed it as a param in the following function
app/code/core/Mage/Sales/Model/Order.php
public function sendNewOrderEmail()
{
/*Existing Code*/
if ($this->getCustomerIsGuest()) {
$templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_GUEST_TEMPLATE, $storeId);
$customerId = Mage::getModel('customer/customer')->load($this->getCustomerId());
$companyname = $customerId->getCompanyname();
$customerName = $this->getBillingAddress()->getName();
} else {
$templateId = Mage::getStoreConfig(self::XML_PATH_EMAIL_TEMPLATE, $storeId);
$customerId = Mage::getModel('customer/customer')->load($this->getCustomerId());
$companyname = $customerId->getCompanyname();
$customerName = $this->getCustomerName();
}
/*Existing Code*/
$mailer->setTemplateParams(array(
'order' => $this,
'billing' => $this->getBillingAddress(),
'payment_html' => $paymentBlockHtml,
'companyname' => $companyname
));
/*Rest of the code remains the same*/
}
After making this change. I edited my Transactional Email to include this param. Since I wanted to display inside Shipping Address, I placed my variable just before this line in
System > Transactional Emails > New Order Email
{{ var companyname }}
{{var order.getShippingAddress.format('html')}}
If your companyname is getting saved as a part of Customer Information then this would get displayed in your Order Email in 'Shipping Address' Information right at the Start.
You can do the same for Invoice and Shipment Emails.
Hope this helps someone !!! :-)

Categories