I am developing web application using Laravel. In this application I have to send email to the user. Now I want to send those emails using MailChimp. Can anyone guide me how can I send one to one email using MailChimp in Laravel.
I am using below code to send email please check and let me know what to do to send email
$apikey = '<key>-us12';
$to_emails = array('test#gmail.com');
$to_names = array('test');
$message = array(
'html' => 'Yo, this is the <b>html</b> portion',
'text' => 'Yo, this is the *text* portion',
'subject' => 'This is the subject',
'from_name' => 'OMO CRM',
'from_email' => 'customerservice#test.com',
'to_email' => $to_emails,
'to_name' => $to_names
);
$tags = array('WelcomeEmail');
$params = array(
'apikey' => $apikey,
'message' => $message,
'track_opens' => true,
'track_clicks' => false,
'tags' => $tags
);
$url = "https://us12.api.mailchimp.com/3.0/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
curl_close($ch);
$data = json_decode($result);
echo "Status = " . $data->status . "\n";
I am not able to send email using above code.
Related
Hello guys I am trying to update a contact in my list with CRUL. I think everything looks great, only one think that I don't understand is {subscriber_hash}. How can i get this? Or maybe thats not a problem
I get this response
Exists","status":400,"detail":"example#example.com is already a list member. Use PUT to insert or update list members.","instance":"a5de431b-3b5a-3149-1fe3-bc1f6d08ec24"}
But my code looks good i think
$list_id = '[LISTID]';
$authToken = '[APIKEY]';
$postData = array(
"email_address" => "example#example.com",
"status" => "subscribed"
);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://us12.api.mailchimp.com/3.0/lists/'.$list_id.'/members/{subscriber_hash}',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode($postData),
CURLOPT_HTTPHEADER => array(
'Authorization: apikey '.$authToken,
"cache-control: no-cache",
"content-type: application/json"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
This is the working code finally
$list_id = 'LISTID';
$authToken = 'APIKEY';
// The data to send to the API
$postData = array(
"email_address" => "example#example.com",
"status" => "subscribed",
"firstname" => "asd",
"lastname" => "asda"
);
$data = $postData;
function syncMailchimp($data) {
$apiKey = 'APIKEY';
$listId = '0LISTID';
$memberId = md5(strtolower($data['email_address']));
$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_address'],
'status' => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => [
'FNAME' => 'asd',
'LNAME' => 'asd'
]
]);
$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, 'PATCH');
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);
return $result;
}
$res = syncMailchimp($data);
print_r($res);
I am developing a small script and I am bit messed up.
I'm parsing csv file as list of phone Nos to receive bulk SMS notification.
The csv file record is in the form of 1 phone No column contains all phone Nos
the app is first allow the user to upload csv file then it shows them to the user in order to prepare a text message to be sent.
The app is working but no SMS received.
I wish if some help me with phone No array.
(code from comment 1)
if (count($data) > 0) {
if ($request->has('header')) {
$csv_header_fields = [];
foreach ($data[0] as $key => $value) {
$csv_header_fields[] = $key;
}
}
$csv_data = $data;
$csv_data_file = CsvData::create([
'csv_filename' => request->file('csv_file')->getClientOriginalName(),
'csv_header' => $request->has('header'),
'csv_data' => json_encode($data)
]);
} else {
return redirect()->back();
}
(code from comment 2)
$json = array();
$mobile_phone = $data;
$message = $notes ." \Hello";
$mobile_phone_array = str_split($mobile_phone);
$sms = array( 'number' => $mobile_phone, 'message' => $message, 'key' => '123' );
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, '10.192.100.180/NoranAPI/default.aspx');
curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($sms));
$result_sms = curl_exec($ch);
I use the Mailchimp API to first get the marketing_permission_id for my list. The response looks like this
[marketing_permission_id] => f878932739
This value is then used in a second api call to update the settings for a specific user. However, I get the error:
string(227)
"{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Bad
Request","status":400,"detail":"Marketing permission ID '' does not
exist.", [...]
I double checked the data that is being send in the second call and it has the correct marketing_permission_id in there:
{"marketing_permissions":{"marketing_permission_id":"f878932739","enabled":true}}
I followed the format from https://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/#%20.
I don't understand what's going wrong. Hopefully someone here does.. :)
Just leaving this for future reference - there're not many hints on google for mailchimp API with marketing permissions...
This is the basic function i use for adding a contact to a list.
function syncMailchimp($userdata,
$apiKey, $listId)
{
$dataCenter = substr($apiKey,
strpos($apiKey, '-') +
1);
$url = 'https://'.$dataCenter.
'.api.mailchimp.com/3.0/lists/'
.$listId.
'/members/';
// This is the interesting part //
$json = json_encode([
'email_address' => $userdata[
'email'],
'status' => $userdata['status'], // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => [
'FNAME' => $userdata[
'firstname'
],
'LNAME' => $userdata['lastname']
],
'tags' => [
'added'
],
// How to build the Array -->
'marketing_permissions' =>
array(
0 =>
array(
'marketing_permission_id' =>
'1e5142bbce',
'enabled' =>
true,
),
),
]);
$ch = curl_init($url);
curl_setopt($ch,
CURLOPT_HTTPAUTH,
CURLAUTH_BASIC);
$headers = array(
'Content-Type:application/json',
'Authorization: apikey '
.$apiKey
);
curl_setopt($ch,
CURLOPT_HTTPHEADER,
$headers);
curl_setopt($ch,
CURLOPT_RETURNTRANSFER,
true);
curl_setopt($ch,
CURLOPT_TIMEOUT, 10);
curl_setopt($ch,
CURLOPT_CUSTOMREQUEST,
'POST');
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);
return $result;
}
** I am building a emailing techniques with mailchimp i want to store
data in the lists how can i insert data in the list of mailchimp
campaign ?**
is there any kind of api or something else i am new to it.
I am using laravel to do this. data store in mysql but how to start saving it in the mailchimp list ?
This will help you
class MailChimpController extends Controller
{
public function add( Request $request ) {
$apikey="api key-us17";
$server = "us17.";
$listid = 'list id';
if ( $request->isMethod( 'post' ) ) {
//try {
$request_data = $request->all();
$email =$request_data['email'];
$request_data['earlyprice'] = isset($request_data['earlyprice']) ? floatval($request_data['earlyprice']) : 0.0 ;
$request->merge(['earlyprice' => $request_data['earlyprice']]);
$request_data['gaprice'] = isset($request_data['gaprice']) ? floatval($request_data['gaprice']) : 0.0 ;
$request->merge(['gaprice' => $request_data['gaprice']]);
$this->validate( $request, [
'title' => 'required|max:255',
'location' => 'required|max:255',
'starttime' => 'required',
'category' => 'required',
'type' => 'required',
'image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048|dimensions:min_width=360,min_height=261',
'description' => 'required|max:1000',
'fullname' => 'required|max:255',
'phone' => 'required|max:255',
'email' => 'required|max:255',
'website' => 'required',
'socialmedia' => 'required'
] );
$event = new \App\CustomerEvent();
$imageName = "";
if ( $request->hasFile( 'image' ) ) {
$imageName = md5( time() ) . '.' . $request->image->getClientOriginalExtension();
$request->image->move( public_path( 'events_images' ), $imageName );
}
$requestData = $request->all();
$requestData['image'] = $imageName;
$requestData['status'] = "D";
$requestData['eventkey'] = $this->generate_key();
$event->fill( $requestData );
$x = $event->save();
$auth = base64_encode( 'user:'.$apikey );
$data = array(
'apikey' => $apikey,
'email_address' => $email,
'status' => 'subscribed',
);
$json_data = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'Pathto ur trigger');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('content-type: application/json','Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
//return redirect()->back()->with( 'status', 'Event created' );
} else {
return view( 'events.host.index' );
}
}
I have a list with these fields: email, FNAME and LNAME. When I try to send merge_fields via Ajax, the Ajax return an error:
string(400) "{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"f311cff1-ec28-4003-8dde-007bc0001688","errors":[{"field":"merge_fields.FNAME","message":"Data did not match any of the schemas described in anyOf."}]}"
JS:
app.subscribe = function() {
$(document).on('submit', '.form-course', function(e) {
var fullName = $('#name').val(),
arrName = fullName.split(' '),
fname = arrName.slice(0, 1).join(' '),
lname = arrName.slice(1, arrName.length).join(' ');
var data = {
'email' : $('#email').val(),
"merge_fields": {
"FNAME": fname,
"LNAME": lname
}
};
console.log(data);
$.ajax({
url: url+'/wp-admin/admin-ajax.php?action=ux_subscribe',
method: 'POST',
data: data,
success: function(response) {
gtag('send', 'event', 'Modal', 'subscribed', 'Subscription');
fbq('track', 'CompleteRegistration');
$('#modal').fadeOut(function() {
// window.location.replace("./sucesso");
});
}, error: function(data) {
alert('ERRO! Tente novamente mais tarde!');
}
});
return false;
});
};
PHP:
function ux_subscribe() {
//GET via front-end form
$apiKey = 'XXX'; //Generate an API key via: Account > Extras > Api Keys
$listId = 'XXX'; //Find this via: Lists > List > Settings > List name and defaults
$email = $_POST['email']; //GET via front-end form
$fname = $_POST['fname']; //GET via front-end form
$lname = $_POST['lname']; //GET via front-end form
$auth = base64_encode( 'user:' . $apiKey );
echo $fname;
$json = json_encode([
'email_address' => $email,
'status' => "subscribed", // Choices include: "subscribed", "unsubscribed", "cleaned", "pending"
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
]);
$memberId = md5(strtolower( $email ));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json', 'Authorization: Basic ' . $auth]);
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
var_dump($result);
wp_die();
}
If I remove the variables and put a string, it works:
$json = json_encode([
'email_address' => $email,
'status' => "subscribed", // Choices include: "subscribed", "unsubscribed", "cleaned", "pending"
'merge_fields' => array(
'FNAME' => 'hello',
'LNAME' => 'bye'
)
]);
Someone knows why???
You can not send "empty" values to the API.
For example, this will work:
$fname = "joe";
$lname = "smith"
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
But this would fail, notice how the lname is not defined.
$fname = "joe";
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
Therefore you need some simple shorthand to supply "empty" values.
$fname = empty($fname) ? " " : $fname;
$lname = empty($lname ) ? " " : $lname ;
'merge_fields' => array(
'FNAME' => $fname,
'LNAME' => $lname
)
I had a large array with 20 segments in it, and got the same error over and over, once I tossed in some proper empty() checking all was well...
This is old but wanted to point out that your javascript ajax call sends this data:
var data = {
'email' : $('#email').val(),
"merge_fields": {
"FNAME": fname,
"LNAME": lname
}
};
...But your PHP script is trying to find the post variables in:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
Just update your ajax data to this:
var data = {
'email' : $('#email').val(),
'fname': fname,
'lname' : lname
};