I need to add a MailChimp subscriber to a specific grouping. I have no issue getting the subscriber subscribed, but can't seem to get them into a specific grouping.
This is what I have:
// ENTER INTO MAILCHIMP
$newsletter = $_POST['newsletter'];
$newsletter = 'yes';
if ($newsletter = "yes") {
$MailChimp = new \Drewm\MailChimp('api');
$result = $MailChimp->call('lists/subscribe',
array(
'id' => 'listnumber',
'email' => array('email'=> $_POST['usersEmail']),
'merge_vars' => array(
'FNAME'=>$_POST['usersName'], 'LNAME'=>$_POST['usersLastName'],
'groupings' => array(
'id' => 494281,
array(
'name'=>'KeepBoard',
'groups' => 'KeepBoardUsers'
)
)
),
'double_optin' => false,
'update_existing' => true,
'replace_interests' => false,
'send_welcome' => false
));
print_r($result);
}
Also I am not entirely sure where to grab the listing id. I can't seem to find documentation. I worked off the URL. But I don't think that is right because that is the id for all groupings.
For those that have this problem this was the issue. The groups have to be an array, even for a single group.
Related
I'm using the MadelineProto project for php to interact with Telegram API.
Maybe this error has nothing to do with MadelineProto... anyway, I successfully created a supergroup but any other method I call after, gives me a CHAT_WRITE_FORBIDDEN error.
Can't find anything in Telegram Documentation about why I'm getting this error and how to solve.
This is my code:
$MadelineProto = new MadelineProtoAPI('session.madeline', $settings);
$MadelineProto->async(false);
$MadelineProto->start();
// successfully create the group
$updates = $MadelineProto->channels->createChannel([
'megagroup' => true,
'title' => 'Test group',
'about' => 'Test group description',
]);
foreach($updates as $update) {
// try to invite other users --> CHAT_WRITE_FORBIDDEN
$updates = $MadelineProto->channels->inviteToChannel([
'channel' => $update,
'users' => ['########']
]);
// try to change admin rights --> CHAT_WRITE_FORBIDDEN
$updates = $MadelineProto->channels->editAdmin([
'channel' => $update,
'user_id' => '########',
'admin_rights' => [
'_' => 'chatAdminRights',
'change_info' => true,
'post_messages' => true,
'edit_messages' => true,
'delete_messages' => true,
'ban_users' => true,
'invite_users' => true,
'pin_messages' => true,
'add_admins' => true,
'anonymous' => true,
],
'rank' => ''
]);
}
What I'm doing wrong?
Thanks
It seems that the problem was due to the value passed to the 'channel' property. Instead of passing the $update variable, I passed directly the channel id in the form "channel#1234567890" and finally got a correct answer from Telegram.
I'm using the code autogenerated by facebook to try and connect to the marketing API to get campaign stats. In doing so, I'm getting:
Uncaught FacebookAds\Http\Exception\AuthorizationException: (#100) results, actions:like, video_play_actions:video_view, video_avg_time_watched_actions:video_view, unique_actions:link_click are not valid for fields param.
$fields = array(
'results',
'reach',
'actions:like',
'video_play_actions:video_view',
'video_avg_time_watched_actions:video_view',
'unique_actions:link_click',
);
var_dump($fields);
$params = array(
'level' => 'campaign',
'filtering' => array(array('field' => 'campaign.delivery_info','operator' => 'IN','value' => array('active'))),
'breakdowns' => array(),
'time_range' => array('since' => '2017-05-19','until' => '2019-05-19'),
);
echo json_encode((new AdAccount($ad_account_id))->getInsights(
$fields,
$params
)->getResponse()->getContent(), JSON_PRETTY_PRINT);
Above I used campaign.delivery_info per this answer. I've also tried (per the auto-generated code):
'filtering' => array(array('field' => 'delivery_info','operator' => 'IN','value' => array('active')))
Seems you are asking for old values field, try this:
$fields = array(
'reach',
'actions',
'video_play_actions',
'video_avg_time_watched_actions',
'outbound_clicks',
);
Hope this help
NB: results field is not available
It works fine. The groups are created. Emails are subscribed to these groups. But i can't insert the firstname and last name along with it.
foreach($email as $batches){
$fname=$Subscriber['subscriber_firstname'];
$lname=$Subscriber['subscriber_lastname'];
$merge_vars =array(
'fname'=>$fname,
'lname'=>$lname,
'groupings'=>array(
array('id' =>$group_id,
'groups' =>array($group_name)
)
)
);
$batch[] = array('email'=>array('email' =>$batches), $merge_vars);
}
$subscriber = $Mailchimp_Lists -> batchSubscribe($listid,$batch, false, true, true);
print_r($batch);
I had the same issue and found that the documentation on mailchimp is wrong, you need to literally supply the array element 'MERGE_VARS'.
$batch[] = array(
'EMAIL' => array('email' => 'address#example.com'),
'MERGE_VARS' => array(
'FNAME' => 'First Name',
'LNAME' => 'Last Name'
)
);
I have to modify a Zend form where some of the fields can contain decimals. Currently you can only enter your decimals using a point: 34.75)
What I'd like the users to be able is to write their decimals both with a comma or a point. The fields can contain either numbers like 34.75 and 34,75 (In this case, both have the same value). I don't want to modify any configuration on the server, so I need to do this in the code.
Right now the value of some fields is calculated in function of other fields; so when you enter a comma, it messes up the calculations. It's done in javascript, and I'll need to fix those calculations - but for now, I want to fix this issue in the php code when I retrieve the form.
I tried to find a solution on the Zend website, but I didn't find anything I've already read elsewhere with more examples. As you'll see in the code, I need to add either a filter or a validator to a zend_form_element_text. I cannot use a str_replace, as the element is a zend_form_element_text.
I have found this other question for reference.
Here is my resulting code:
$tabBilanFrais = array( 'txtFraisSecretariat' => array( 'nom' => 'Frais secrétariat', 'disabled' => true, "class"=>"calcul"),
'txtFraisRegion' => array( 'nom' => 'Frais région', 'disabled' => false),
'txtFraisSalle' => array( 'nom' => 'Salle', 'disabled' => false, "class"=>"calcul"),
'txtFraisPause' => array( 'nom' => 'Pauses', 'disabled' => false, "class"=>"calcul"),
'txtDivers' => array( 'nom' => 'Divers', 'disabled' => false, "class"=>"calcul"),
'txtTotalRegion' => array( 'nom' => 'Total région', 'disabled' => true, "class"=>"total"),
'txtIndemnisationAdherent' => array( 'nom' => 'Comm. ADH', 'disabled' => true, "class"=>"calcul"),
'txtIndemnisationPAP' => array( 'nom' => 'Comm. PAP', 'disabled' => true, "class"=>"calcul"),
'txtIndemnisationForNext' => array( 'nom' => 'Comm. ForNext', 'disabled' => true, "class"=>"calcul"),
'txtIndemnisationPROStages' => array( 'nom' => 'Comm. PROStages', 'disabled' => true, "class"=>"calcul"),
'txtRecettes' => array( 'nom' => 'Recettes', 'disabled' => true, "class"=>"totalMontant"),
'txtDepenses' => array( 'nom' => 'Dépenses', 'disabled' => true, "class"=>"totalMontant"),
'txtRecettesH' => array( 'nom' => 'Recettes', 'disabled' => false, "class"=>"hiddenTxt"),
'txtDepensesH' => array( 'nom' => 'Dépenses', 'disabled' => false, "class"=>"hiddenTxt")
);
$tabFormulaire = array() ;
foreach($tabBilanFrais as $id => $tabElement)
{
if($tabElement['nom'] == 'Frais region' )
$element = new Zend_Form_Element_Hidden($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
else{
$element = new Zend_Form_Element_Text($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
//$element->addFilter('pregReplace', array('match' => '/,/', 'replace' => '.'));
$element->addFilter('LocalizedToNormalized');
$element->addValidator('float', true, array('locale' => 'fr_FR'));
if(isset($tabElement['class']) && $tabElement['class']){
$element->setAttrib('class', $tabElement['class']);
}
}
if( $tabElement['disabled'])
$element->setAttrib('disabled', 'disabled');
$tabFormulaire[] = $element ;
}
The pregReplace isn't working. The validator is (comma becomes a .). I get an error message about the number not being a float.
You can always write your own validator. In case of float I faced the same problem like you:
class Yourlib_Validate_Float extends Zend_Validate_Abstract
{
const INVALID = 'floatInvalid';
const NOT_FLOAT = 'notFloat';
/**
* #var array
*/
protected $_messageTemplates = array(
self::INVALID => "Invalid type given. String, integer or float expected",
self::NOT_FLOAT => "'%value%' does not appear to be a float",
);
public function isValid($value)
{
$this->_setValue($value);
$value = str_replace(',', '.', $value);
if (!is_string($value) && !is_int($value) && !is_numeric($value)) {
$this->_error(self::INVALID);
return false;
}
if (is_numeric($value)) {
return true;
}
$this->_error(self::NOT_FLOAT);
return false;
}
}
And to add the validator:
$element->addValidator(new Yourlib_Validate_Float());
Please rename Yourlib to whatever suits you. And you need to register your "namespace" in the application.ini like this:
autoloadernamespaces.Yourlib = "Yourlib_"
Strictly speaking this validator is a numeric validator. It accepts all numeric values like ints and floats thru the check with is_numeric. Feel free to modify that.
Alright, here is the modified part of the code:
foreach($tabBilanFrais as $id => $tabElement)
{
if($tabElement['nom'] == 'Frais region' )
$element = new Zend_Form_Element_Hidden($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
else{
$element = new Zend_Form_Element_Text($id, array("label" => $tabElement['nom'], "required" => false, 'decorators' => array("ViewHelper", "Errors", "Label"))) ;
$element->addFilter('pregReplace', array('match' => '/,/', 'replace' => '.'));
$element->addFilter('LocalizedToNormalized');
$element->addValidator(new Anper_Validate_Float(), true, array('locale' => 'fr_FR'));
if(isset($tabElement['class']) && $tabElement['class']){
$element->setAttrib('class', $tabElement['class']);
}
}
if( $tabElement['disabled'])
$element->setAttrib('disabled', 'disabled');
$tabFormulaire[] = $element ;
}
But now I need the values of the fields in $element to have the comma replaced by a point before the element is added to $tabFormulaire. Currently numbers with a comma are truncated (124,5 becomes 124) when I validate the form and display the updated values.
The pregreplace doesn't seem to work.
Edit: it seems I don't need the pregReplace. I used two echo in my isValid function for the custom validator: one before the str_replace and one after. When I write in one of the field a value with a comma, both the echo displays the number with a point. I assume it's the result of the filter LocalizedToNormalized.
What I don't understand is why once the values are saved and displayed those with a comma are truncated despite the findings I just made.
Edit2: If I write for example 124 8, and use a pregReplace to do like there was no blank, the 8 isn't kept on save; despite the pregReplace working (tried with my previous echo).
Although #bitWorking's answer is 100% OK, from the view point of semantics, it's better to use a filter (since it's more of filtering rather than validating)
either NumberFormat filter or writing your own.
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