Using MailChimp API V3.0 to create a campaign.
I want to create a campaign that sends to users with a specific interest. It looks like this is possible in the docs, but I've tried every permutation I can think of. I can create the campaign fine as long as I leave out the segment_ops member. Does anyone have an example of PHP code that will do it?
It seems that interests are handled strangely since you don't include the interest-category when setting a users interests via the API. I'm not sure how this affects campaign creation.
I've gotten this to work, API definition can be found here https://us1.api.mailchimp.com/schema/3.0/Segments/Merge/InterestSegment.json
Interests have to be grouped under interest categories (called 'Groups' in some parts of the UI).
Here is the JSON for the segment_opts member of the recipients array:
"segment_opts": {
"match": "any",
"conditions": [{
"condition_type": "Interests",
"field": "interests-31f7aec0ec",
"op": "interestcontains",
"value": ["a9014571b8", "5e824ac953"]
}]
}
Here is the PHP array version with comments. The 'match' member refers to the the rules in the array of 'conditions'. The segment can match any, all, or none of the conditions. This example has only one condition, but others can be added as additional arrays in the 'conditions' array:
$segment_opts = array(
'match' => 'any', // or 'all' or 'none'
'conditions' => array (
array(
'condition_type' => 'Interests', // note capital I
'field' => 'interests-31f7aec0ec', // ID of interest category
// This ID is tricky: it is
// the string "interests-" +
// the ID of interest category
// that you get from MailChimp
// API (31f7aec0ec)
'op' => 'interestcontains', // or interestcontainsall, interestcontainsnone
'value' => array (
'a9014571b8', // ID of interest in that category
'5e824ac953' // ID of another interest in that category
)
)
)
);
You may also send to a Saved segment. The gotcha on this is that the segment_id has to be int. I was saving this value in a db as varchar, and it would not work unless cast to int.
(i am using use \DrewM\MailChimp\MailChimp;)
$segment_id = (int) $methodThatGetsMySegmentID;
$campaign = $MailChimp->post("campaigns", [
'type' => 'regular',
'recipients' => array(
'list_id' => 'abc123yourListID',
'segment_opts' => array(
'saved_segment_id' => $segment_id,
),
),
'settings' => array(
'subject_line' => 'A New Article was Posted',
'from_name' => 'From Name',
'reply_to' => 'info#example.com',
'title' => 'New Article Notification'
)
]);
Related
I am looking to develop a custom logic hook for our SugarCRM system (uses PHP) which provides the following function:
On Save of a Quote record (either new or update):
IF no contact records have already been linked to the quote THEN
Get contacts linked to the related Opportunity
Link these contacts to the quote
I have created the logic hook as per SugarCRM developer documentation and loaded into our dev instance (we run in SugarCloud) but the hook does not appear to fire. Can anyone help me?
./custom/Extension/modules/Quotes/Ext/LogicHooks/initialiseRecord.php
<?php
$hook_version = 1;
$hook_array['after_save'][] = Array(
//Processing index. For sorting the array.
1,
//Label. A string value to identify the hook.
'after_save example',
//The PHP file where your class is located.
'custom/modules/Quotes/initialise_record.php',
//The class the method is in.
'after_save_initialise_class',
//The method to call.
'after_save_initialise'
);
.custom/modules/Quotes/initialise_record.php
<?php
if (!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
// bean in this context will be Quotes bean being saved
class after_save_initialise_class
{
function after_save_initialise($bean, $event, $arguments)
{
require_once('include/SugarQuery/SugarQuery.php');
$sugarQuery = new SugarQuery();
//Determine if contacts have already been linked
if ($bean->load_relationship('contacts')) {
//Fetch related beans
$relatedBeans = $bean->contacts->get();
// If no contacts have already been connected then initialise. Otherwise abort.
if (count($relatedBeans) === 0) {
// Step 1: Get Opportunity related to quote.
if ($bean->load_relationship('opportunities')) {
//Fetch related beans
$relatedOpportunityBeans = $bean->opportunities->get();
//Retrieve the bean id of the linked opportunity record
$opportunity_record_id = $relatedOpportunityBeans[0];
// Step 2: Get Contacts linked to Opportunity
//Retrieve Opportunity bean
$opportunity_bean = BeanFactory::retrieveBean('Opportunities', $opportunity_record_id);
if ($opportunity_bean->load_relationship('contacts')) {
//Retrieve all contacts connected to that opportunity
$relatedContactBeanIds = $bean->contacts->get();
// Loop through these adding them to the quote bean
foreach ($relatedContactBeanIds as &$value) {
// quotes_contacts_1 is the name of custom many-to-many relationship in SugarCRM between the Quotes and Contacts module created in 'Studio' within SugarCRM
$bean->quotes_contacts_1->add($value);
};
};
};
}
}
}
}
.manifest.php {Used by SugarCRM Package Loader to install the package}
<?php
$manifest = array(
'key' => 202106270819,
'name' => 'Sync Contacts To Quote',
'description' => 'Adds Custom Logic Hook to Sync Contacts from Opportunity to Quote Level',
'author' => 'TBC',
'version' => '1.0',
'is_uninstallable' => true,
'type' => 'module',
'acceptable_sugar_versions' =>
array(
'regex_matches' => array(
'11.0.*' //any 11.0 release
),
),
'acceptable_sugar_flavors' =>
array(
'PRO',
'ENT',
'ULT'
),
'readme' => '',
'icon' => '',
'remove_tables' => '',
'uninstall_before_upgrade' => false,
);
$installdefs = array (
'id' => 'SyncContactOpportunityQuote',
'hookdefs' => array(
array(
'from' => '<basepath>/custom/Extension/modules/Quotes/Ext/LogicHooks/initialiseRecord.php',
'to_module' => 'application',
)
),
'copy' => array(
0 => array(
'from' => '<basepath>/custom/modules/Quotes/initialise_record.php',
'to' => 'custom/modules/Quotes/initialise_record.php'
)
)
);
?>
References:
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_11.0/Architecture/Logic_Hooks/
https://support.sugarcrm.com/Documentation/Sugar_Developer/Sugar_Developer_Guide_11.0/Data_Framework/Models/SugarBean/#Updating_a_Bean
Does your Hook get executed at all? How did you verify that it does or doesn't?
If it does get loaded, I suspect that it skips/quits at
//Determine if contacts have already been linked
if ($bean->load_relationship('contacts')) {
//Fetch related beans
$relatedBeans = $bean->contacts->get();
contacts in 2nd and last line isn't an actual field in Quotes, is it?
Did you mean to use quotes_contacts_1 in those two places?
(Which you referred to farther below)
Also with regards to the manifest.php:
I'm not familiar with hookdefs (I just use regular copy to install the hook file), but 'to_module' => 'application',, seems odd - don't you mean 'to_module' => 'Quotes',?
To get related contacts from opportunities
$opp = $bean->opportunities->getBeans();
$opportunity_record_id = $opp->id;
I want to filter list that does not have an invalid email and opt-out email in Leads and Contact module using SugarCRM 7 API.
I have added below email filter in arguments but does not work. How to email filter via SugarCRM 7.x rest API.
$filter_arguments = array(
"filter" => array(
array(
"assigned_user_id" => 1,
),
array(
"email1" => array(
array(
'opt_out' => array(
'$equals' => ''
)
)
)
),
),
);
$url = $base_url . "/Contacts/filter";
Thanks.
This much code will not help you please check this :
Reference Link 1
Reference Link 2
The following example will demonstrate how to add a predefined filter on the Accounts module to return all records with an account type of "Customer" and industry of "Other".
To create a predefined filter, create a display label extension in ./custom/Extension/modules/<module>/Ext/Language/. For this example, we will create:
./custom/Extension/modules/Accounts/Ext/Language/en_us.filterAccountByTypeAndIndustry.php
<?php
$mod_strings['LBL_FILTER_ACCOUNT_BY_TYPE_AND_INDUSTRY'] = 'Customer/Other Accounts';
Next, create a custom filter extension in ./custom/Extension/modules/<module>/Ext/clients/base/filters/basic/.
For this example, we will create:
./custom/Extension/modules/Accounts/Ext/clients/base/filters/basic/filterAccountByTypeAndIndustry.php
<?php
$viewdefs['Accounts']['base']['filter']['basic']['filters'][] = array(
'id' => 'filterAccountByTypeAndIndustry',
'name' => 'LBL_FILTER_ACCOUNT_BY_TYPE_AND_INDUSTRY',
'filter_definition' => array(
array(
'account_type' => array(
'$in' => array(
'Customer',
),
),
),
array(
'industry' => array(
'$in' => array(
'Other',
),
),
),
),
'editable' => false,
'is_template' => false,
);
You should notice that the editable and is_template options have been set to "false". If editable is not set to "false", the filter will not be displayed in the list view filter's list.
Finally, navigate to Admin > Repair and click "Quick Repair and Rebuild" to rebuild the extensions and make the predefined filter available for users.
Adding Initial Filters to Lookup Searches
To add initial filters to record lookups and type-ahead searches, define a filter template. This will allow you to filter results for users when looking up a parent related record. The following example will demonstrate how to add an initial filter for the Account lookup on the Contacts module. This initial filter will limit records to having an account type of "Customer" and a dynamically assigned user value determined by the contact's assigned user.
To add an initial filter to the Contacts record view, create a display label for the filter in ./custom/Extension/modules/<module>/Ext/Language/. For this example , we will create:
./custom/Extension/modules/Accounts/Ext/Language/en_us.filterAccountTemplate.php
<?php
$mod_strings['LBL_FILTER_ACCOUNT_TEMPLATE'] = 'Customer Accounts By A Dynamic User';
Next, create a custom template filter extension in ./custom/Extension/modules/<module>/Ext/clients/base/filters/basic/.
For this example, create:
./custom/Extension/modules/Accounts/Ext/clients/base/filters/basic/filterAccountTemplate.php
<?php
$viewdefs['Accounts']['base']['filter']['basic']['filters'][] = array(
'id' => 'filterAccountTemplate',
'name' => 'LBL_FILTER_ACCOUNT_TEMPLATE',
'filter_definition' => array(
array(
'account_type' => array(
'$in' => array(),
),
),
array(
'assigned_user_id' => ''
)
),
'editable' => true,
'is_template' => true,
);
As you can see, the filter_definition contains arrays for account_type and assigned_user_id. These filter definitions will receive their values from the contact record view's metadata. You should also note that this filter has is_template and editable set to "true". This is required for initial filters.
Once the filter template is in place, modify the contact record view's metadata. To accomplish this, edit ./custom/modules/Contacts/clients/base/views/record/record.php to adjust the account_name field. If this file does not exist in your local Sugar installation, navigate to Admin > Studio > Contacts > Layouts > Record View and click "Save & Deploy" to generate it. In this file, identify the panel_body array as shown below:
1 =>
array (
'name' => 'panel_body',
'label' => 'LBL_RECORD_BODY',
'columns' => 2,
'labelsOnTop' => true,
'placeholders' => true,
'newTab' => false,
'panelDefault' => 'expanded',
'fields' =>
array (
0 => 'title',
1 => 'phone_mobile',
2 => 'department',
3 => 'do_not_call',
4 => 'account_name',
5 => 'email',
),
),
Next, modify the account_name field to contain the initial filter parameters.
1 =>
array (
'name' => 'panel_body',
'label' => 'LBL_RECORD_BODY',
'columns' => 2,
'labelsOnTop' => true,
'placeholders' => true,
'newTab' => false,
'panelDefault' => 'expanded',
'fields' =>
array (
0 => 'title',
1 => 'phone_mobile',
2 => 'department',
3 => 'do_not_call',
4 => array (
//field name
'name' => 'account_name',
//the name of the filter template
'initial_filter' => 'filterAccountTemplate',
//the display label for users
'initial_filter_label' => 'LBL_FILTER_ACCOUNT_TEMPLATE',
//the hardcoded filters to pass to the templates filter definition
'filter_populate' => array(
'account_type' => array('Customer')
),
//the dynamic filters to pass to the templates filter definition
//please note the index of the array will be for the field the data is being pulled from
'filter_relate' => array(
//'field_to_pull_data_from' => 'field_to_populate_data_to'
'assigned_user_id' => 'assigned_user_id',
)
),
5 => 'email',
),
),
Finally, navigate to Admin > Repair and click "Quick Repair and Rebuild". This will rebuild the extensions and make the initial filter available for users when selecting a parent account for a contact.
Adding Initial Filters to Drawers from a Controller
When creating your own views, you may need to filter a drawer called from within your custom controller. Using an initial filter, as described in the Adding Initial Filters to Lookup Searches section, we can filter a drawer with predefined values by creating a filter object and populating the config.filter_populate property as shown below:
//create filter
var filterOptions = new app.utils.FilterOptions()
.config({
'initial_filter': 'filterAccountTemplate',
'initial_filter_label': 'LBL_FILTER_ACCOUNT_TEMPLATE',
'filter_populate': {
'account_type': ['Customer'],
'assigned_user_id': 'seed_sally_id'
}
})
.format();
//open drawer
app.drawer.open({
layout: 'selection-list',
context: {
module: 'Accounts',
filterOptions: filterOptions,
parent: this.context
}
});
To create a filtered drawer with dynamic values, create a filter object and populate the config.filter_relate property using the populateRelate method as shown below:
//record to filter related fields by
var contact = app.data.createBean('Contacts', {
'first_name': 'John',
'last_name': 'Smith',
'assigned_user_id': 'seed_sally_id'
});
//create filter
var filterOptions = new app.utils.FilterOptions()
.config({
'initial_filter': 'filterAccountTemplate',
'initial_filter_label': 'LBL_FILTER_ACCOUNT_TEMPLATE',
'filter_populate': {
'account_type': ['Customer'],
},
'filter_relate': {
'assigned_user_id': 'assigned_user_id'
}
})
.populateRelate(contact)
.format();
//open drawer
app.drawer.open({
layout: 'selection-list',
context: {
module: 'Accounts',
filterOptions: filterOptions,
parent: this.context
}
});
I am trying to implement the 'InArray' validator in Zend 2 on a form and it keeps on returning invalid. Here is the code:
The Form Element setup:
$enquiryType = new Element\Select('enquiryType');
$enquiryType->setLabel('* What is your enquiry about?')
->setLabelAttributes(array('class' => 'sq-form-question-title'))
->setAttribute('class', 'sq-form-field required')
->setValueOptions($enquiryTypes);
The Filter/Validator setup:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => $enquiryTypes));
And here is the array that gets passed into $enquiryTypes via the module.config.php file
'enquiryCategories' => array(
'empty_option' => 'Please select an option',
array(
'label' => 'General enquiries',
'options' => array(
'skype' => 'Skype with your library feedback',
'question' => 'Ask a question',
'feedback' => 'Library feedback',
'eresource' => 'Electronic resources (e.g. e-book, e-journal, database)',
'webbridge' => 'WebBridge Problems',
'dro' => 'DRO'
)
),
array(
'label' => 'Application to review',
'options' => array(
'10400' => 'I\'ve returned the item',
'10401' => 'I didn\'t know about overdue points but now I have some',
'10402' => 'Why did I get this invoice?',
'10403' => 'The item I borrowed is lost',
'10404' => 'The item I borrowed has been damaged',
'10405' => 'I never got/had the book',
'10406' => 'Other'
)
)
),
I have tried different variations of this (using the recursive validation also) but have not been able to work this out.
One thing that I'd try, is as follows:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => $enquiryTypes['enquiryCategories']));
The reason I say that, is that it looks like you might be creating an array inside of the array perhaps. Unless I've misunderstood the description.
If that isn't working for you then maybe you might need to explore the Explode option as pointed out in the following question
ZF2: How do I use InArray validator to validate Multiselect form element?
Good luck.
I finally got a working solution for this. I feel there should be a better solution but I could not find one.
Here is the filter I used:
$enquiryType = new Input('enquiryType');
$enquiryType->getValidatorChain()
->addByName('InArray', array('haystack' => array_keys(
$enquiryTypes[0]['options']+$enquiryTypes[1]['options']
)));
$enquiryType->getFilterChain()
->attach(new Filter\StringToLower())
->attachByName('StripTags');
Basically I had to disect the array options into a straight associative array. As the array remains static in this instance then this works well.
If the data becomes dynamic then something more would be required (loop through and find the 'option' key, add children to filter array etc...)
is there a away to translate values in php using either google api translate or any other api...
<?php
// 1.- Query to get information
// 2.- build array with that query
// Example array from query
$data = array(
'0' => array (
'name' => 'Zapatos',
'color' => 'Verde'
),
'1' => array (
'name' => 'Casa',
'color' => 'Rosa'
),
);
// Now that the array has been build, lets make a translation
// Which I have no idea how to do that but the final array should be
$final = array(
'0' => array (
'name' => 'Zapatos',
'color' => 'Verde',
'name_en' => 'Shoes',
'color_en' => 'Green'
),
'1' => array (
'name' => 'Casa',
'color' => 'Rosa',
'name_en' => 'House',
'color_en' => 'Pink'
),
);
is this process possible or am I just dreaming?
I have very little knowledge on how exactly Goolge API works since I only use the Google Translate widget and the translation is after you present the information but in this case we need to make a translation before presenting the information...
Google translate API is a paid service. You need to get a api key from google api services :
google translate API
After that, you can make a curl to google api after getting your results from query :
sample url for curl :
https://www.googleapis.com/language/translate/v2?key=INSERT-YOUR-KEY&source=en&target=de&q=Hello%20world&q=My%20name%20is%20Jeff
You will get the results as JSON object,do json_decode and add results to your array.
I'm currently using the MailChimp API for PHP, version 1.3.1 (http://apidocs.mailchimp.com/api/downloads/#php)
I've set up a list in MailChimp, and would like to dynamically add:
Subscribers to the list (done: $objMailChimp->listBatchSubscribe($strMailingListID, ...))
Interest Groupings (done: $objMailChimp->listInterestGroupingAdd($strMailingListID, ...))
Interest Groups into those Groupings (done: $objMailChimp->listInterestGroupAdd($strMailingListID, ...))
Subscribers assigned to relevant Groups (not done)
The API (http://apidocs.mailchimp.com/api/1.3/#listrelated) is somewhat unclear on how to add a subscriber to an interest group - does anyone here have any ideas?
As of version 2.0 of MailChimp's API, this should work:
$merge_vars = array(
'GROUPINGS' => array(
array(
'name' => "GROUP CATEGORY #1", // You can use either 'name' or 'id' to identify the group
'groups' => array("GROUP NAME","GROUP NAME")
),
array(
'name' => "GROUP CATEGORY #2",
'groups' => array("GROUP NAME")
)
)
);
Source: http://apidocs.mailchimp.com/api/2.0/lists/subscribe.php
Using a barebones PHP wrapper (https://github.com/drewm/mailchimp-api/) you can then send this to MailChimp via either the lists/subscribe or lists/batch-subscribe:
$MailChimp = new MailChimp('API_KEY');
$result = $MailChimp->call('lists/subscribe', array(
'id' => 'LIST ID',
'email' => array('email'=>'trevor#example.com'),
'merge_vars' => $merge_vars
));
For MailChimp API v3
As of v3, 'groupings' has changed to 'interests'.
You have to find out the ID of the group (interest) that you are wanting to add to. Unfortunately this cannot be found anywhere on the MailChimp dashboard.
The easiest way to find out the 'interest' ID (rather than creating a script) is to go to the MailChimp playground and then, after entering in your API key, route to...
lists > the list in question > interest-categories (in the sub-resources dropdown)
then...
interests (in the sub-resources dropdown) for interest category
then...
Click through to the interest and refer to the 'id' field, ignoring the other ID fields
OR
lists > the list in question > members (in the sub-resources dropdown)
then...
load (in the actions dropdown) for any member
or
Create Members (button)
The page will load the member's details. Scroll down until you see the 'interests' array/object. There you will see the IDs. Notice they can be set to true or false.
You will have to figure out which ID relates to what 'group'/'interest' by going about the previous method or making the call, and then looking at the member's details via your MailChimp dashboard.
So when it comes to actually making the POST call ('member' create), you would want something on the lines of...
{
"email_address":"example#freddiesjokes.com",
"status":"subscribed",
"interests": {
"b8a9d7cbf6": true,
"5998e44916": false
},
# ADDITIONAL FIELDS, IF REQUIRED...
"merge_fields":{
"FNAME": "foo bar",
"LNAME": "foo bar",
"MERGE3": "foo bar",
"MERGE4": "foo bar"
}
}
A PUT call ('member' edit) example...
{
"interests": {
"b8a9d7cbf6": false,
"5998e44916": true
}
}
It seems that you must declare every 'interest', and state whether it is true or false.
I could not get the other answers on this page to work. Here's the merge vars that I had to use:
$merge_vars = array(
'GROUPINGS' => array(
0 => array(
'id' => "101", //You have to find the number via the API
'groups' => "Interest Name 1, Interest Name 2",
)
)
);
Use GROUPINGS merge var:
Set Interest Groups by Grouping. Each element in this array should be
an array containing the "groups" parameter which contains a comma
delimited list of Interest Groups to add. Commas in Interest Group
names should be escaped with a backslash. ie, "," => "\," and either
an "id" or "name" parameter to specify the Grouping - get from
listInterestGroupings()
Here's the code I got to work
require_once 'MCAPI.class.php';
require_once 'config.inc.php'; //contains apikey
// use this once to find out id of interest group List
//$retval = $api->listInterestGroupings($listId);
//echo '<pre>';
//print_r($retval);
//echo '</pre>';
//die();
$emailAddress = 'info#example.com';
//You have to find the number via the API (id of interest group list)
$interestGroupListId = FILLMEIN;
$api = new MCAPI($apikey);
// Create an array of Interest Groups you want to add the subscriber to.
$mergeVars = array(
'GROUPINGS' => array(
0 => array(
'id' => $interestGroupListId,
'groups' => "FILL IN GROUP NAMES",
)
)
);
// Then use listUpdateMember to add them
$retval = $api->listUpdateMember($listId, $emailAddress, $mergeVars);
if ($api->errorCode){
echo "Unable to update member info!\n";
echo "\tCode=".$api->errorCode."\n";
echo "\tMsg=".$api->errorMessage."\n";
} else {
echo "Returned: ".$retval."\n";
}
This is a variation of Justins answer but having tried all the above this is the only one I could get to work with DrewM's MailChimp wrapper
$merge_vars = array(
'GROUPINGS' => array(
0 => array(
'id' => '[GROUP_LIST_ID]', // need grouping ID
'name' => '[OR_GROUP_LIST_NAME]', // or name instead
'groups' => array( '[GROUP_NAME_1]', '[GROUP_NAME_2]' )
)
),
);
$mc = new MailChimp('[YOUR_MAILCHIMP_API]');
$mc->call(
'lists/subscribe', array(
'id' => '[YOUR_LIST_ID]', // list ID
'email' => array( 'email' => 'someone#something.com'),
'merge_vars' => $merge_vars,
'double_optin' => true,
'update_existing' => true,
'replace_interests' => false, // do you want to add or replace?
'send_welcome' => false,
)
);
If you are unsure of your groups lists ID and wish to use it you can call:
$current_groupings = $mc->call( 'lists/interest-groupings', array(
'id' => '[GROUP_LIST_ID]',
) );
var_dump($current_groupings);
Also please note optional but very important last parameter of listUpdateMember, by default replace_interests it set to true so it will overwrite any subscription the user you are updating could have had in the past. If you want to add new ones not touching previous ones just pass the new group name you wanna add and set replace_interests to false.
$api = new MailChimp('API_KEY');
$pArray = array('GROUPINGS'=>array(
array('name'=>'GROUP CATEGORY', 'groups'=>'group1,group2'),
)
);
if (is_array($pArray)) {
$api->listUpdateMember($pListId, $pEmail, $pArray, '', false);
}
Example using DrewM's MailChimp wrapper and shorthand syntax for arrays (PHP 5.4+) add to groups:
$merge_vars = [
'GROUPINGS' => array(
0 => [
'id' => 12345, // need grouping ID
'name' => 'Interests', // or name instead
'groups' => [ 'cars', 'trucks' ]
]
]
];
$mc = new MailChimp('API_KEY');
$mc->call(
'lists/subscribe', [
'id' => '9876', // list ID
'email' => array[ 'email' => 'example#abc.com' ],
'merge_vars' => $merge_vars,
'double_optin' => true,
'update_existing' => true,
'replace_interests' => false, // do you want to add or replace?
'send_welcome' => false,
]
);
You need grouping 'name' OR 'id', both are not needed. To get grouping ID use: lists/interest-groupings