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);
Related
I am trying to send push notification using google firebase , but notification is not coming to phone
public function pushNotificationToUsersTest(){
$apikey = env('FCM_SERVER_KEY');
$deviceToken = array("deviceTocken_1,deviceTocken_2");
$url = 'https://fcm.googleapis.com/fcm/send';
$message = "Message from server";
foreach ($deviceToken as $key => $Token) {
$preview_message = "ACTIONABLE";
$sound = "default";
$fields = array(
'to' => $Token,
'data' => array(
'message' => $message,
'notification_type' => "message_type",
'message_content' => "message_content",
'chat_type' => "chat_type",
'badge' => 10,
'category' => $preview_message,
'sound' => $sound,
)
);
//header with content_type api key
$headers = array(
'Content-Type:application/json',
'Authorization:key='.$apikey
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
$result = curl_exec($ch);
curl_close($ch);
}
print_r($result);
}
When I print Result I am getting like this
{"multicast_id":1610930223174111380,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1657873770379569%73be5013f9fd7ecd"}]}1
When I checked respose code
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
It gives output 400.
Don't know what the issue
Try to get Access Token From Instagram
$params = array(
'app_id' => $this->clientId,
'app_secret' => $this->clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUrl,
'code' => $this->request->code
);
$ch = curl_init();
$endpoint = $this->getBaseUrl() . 'oauth/access_token';
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 1);
$response = curl_exec($ch);
curl_close($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
dd($response,$header_size,$header,$body);
$response = json_decode($response, true);
return $response;
this code with CURL working fine.
Request Data Laravel Documentation.
$response = Http::post($this->getBaseUrl() . 'oauth/access_token', [
'app_id' => $this->clientId,
'app_secret' => $this->clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUrl,
'code' => $this->request->code
]
);
return $response->body();
but not working with Laravel Http Client.it return Client Id is missing but I'm sending as parameter.
I guess your content type is application/x-www-form-urlencoded, try to use asForm(),
$response = Http::asForm()->post($this->getBaseUrl() . 'oauth/access_token', [
'app_id' => $this->clientId,
'app_secret' => $this->clientSecret,
'grant_type' => 'authorization_code',
'redirect_uri' => $this->redirectUrl,
'code' => $this->request->code
]
);
return $response->json();
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
};